• POJ 1159 Palindrome【LCS+滚动数组】【水题】


    Palindrome
    Time Limit: 3000MS   Memory Limit: 65536K
    Total Submissions: 63833   Accepted: 22254

    Description

    A palindrome is a symmetrical string, that is, a string read identically from left to right as well as from right to left. You are to write a program which, given a string, determines the minimal number of characters to be inserted into the string in order to obtain a palindrome. 

    As an example, by inserting 2 characters, the string "Ab3bd" can be transformed into a palindrome ("dAb3bAd" or "Adb3bdA"). However, inserting fewer than 2 characters does not produce a palindrome. 

    Input

    Your program is to read from standard input. The first line contains one integer: the length of the input string N, 3 <= N <= 5000. The second line contains one string with length N. The string is formed from uppercase letters from 'A' to 'Z', lowercase letters from 'a' to 'z' and digits from '0' to '9'. Uppercase and lowercase letters are to be considered distinct.

    Output

    Your program is to write to standard output. The first line contains one integer, which is the desired minimal number.

    Sample Input

    5
    Ab3bd

    Sample Output

    2

    Source


    给你一个字符串,可在任意位置添加字符,最少再添加几个字符,可以使这个字符串成为回文字符串。
    设原序列S的逆序列为S' ,则最少需要补充的字母数 = 原序列S的长度 —  S和S'的最长公共子序列长度


    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <cmath>
    #include <queue>
    #include <string>
    #include <map>
    #include <cstring>
    #define INF 0x3f3f3f3f
    #define ms(x,y) memset(x,y,sizeof(x))
    using namespace std;
    
    typedef long long ll;
    typedef unsigned long long ull;
    typedef pair<int, int> P;
    
    const int maxn = 5010;
    const int mod = 998244353;
    
    int dp[2][maxn];
    
    int main()
    {
    	string a, b;
    	int n;
    	cin >> n;
    	cin >> a;
    	b = a;
    	reverse(a.begin(), a.end());
    	int ans = -INF;
    	for (int i = 0; i < n; i++)
    	{
    		for (int j = 0; j < n; j++)
    		{
    			if (a[i] == b[j])
    				dp[i % 2][j] = dp[(i + 1) % 2][j - 1] + 1;
    			else
    				dp[i % 2][j] = max(dp[i % 2][j - 1], dp[(i + 1) % 2][j]);
    			ans = max(ans, dp[i % 2][j]);
    		}
    	}
    	cout << n - ans;
    	return 0;
    }




    Fighting~
  • 相关阅读:
    java基础梳理--朝花夕拾(三)
    java基础梳理--朝花夕拾(二)
    [C++] 分治法之棋盘覆盖、循环赛日程表
    [C++] 递归之全排列问题、半数集
    蓝桥杯 算法训练 ALGO-143 字符串变换
    蓝桥杯 算法训练 ALGO-129 特殊的数字四十
    蓝桥杯 算法训练 ALGO-126 水仙花
    蓝桥杯 算法训练 ALGO-122 未名湖边的烦恼
    蓝桥杯 算法训练 ALGO-121 猴子分苹果
    蓝桥杯 算法训练 ALGO-116 最大的算式
  • 原文地址:https://www.cnblogs.com/Archger/p/8451611.html
Copyright © 2020-2023  润新知