zoukankan      html  css  js  c++  java
  • POJ 1159:Palindrome 最长公共子序列

    Palindrome
    Time Limit: 3000MS   Memory Limit: 65536K
    Total Submissions: 56273   Accepted: 19455

    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

    题意是要求给定的字符串添加多少个会变成回文字符串,实际上就是要比较该字符串和它的逆序字符串的最长公共子序列,而不是字串!!!(之前WA就WA在这里),再用长度-最长公共子序列的长度就是结果。

    代码:

    #include <iostream>
    #include <algorithm>
    #include <cmath>
    #include <vector>
    #include <string>
    #include <cstring>
    #pragma warning(disable:4996)
    using namespace std;
    
    short int dp[5002][5002];
    char b[5002];
    string b_reverse;
    int num;
    
    void cal()
    {
    	int i,j,max_value=0;
    
    	memset(dp,0,sizeof(dp));
    
    	for(i=0;i<num;i++)
    	{
    		for(j=0;j<num;j++)
    		{
    			if(b[i]==b_reverse[j])
    			{
    				dp[i+1][j+1]=dp[i][j]+1;
    			}
    			else
    			{
    				dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
    			}
    			max_value=max(max_value,(int)dp[i+1][j+1]);
    		}
    	}
    	cout<<num-max_value<<endl;
    }
    
    int main()
    {
    	scanf("%d",&num);
    	scanf("%s",b);
    
    	b_reverse=b;
    	reverse(b,b+num);
    
    	cal();
    
    	return 0;
    }
    



    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    php 学习笔记 数组2
    php 学习笔记 数组1
    jQuery prop 全选和全不全
    jquery获取多个checkbox的值异步提交给php
    php 计算多维数组中所有值的总和
    系统状态码原型
    hadoop win10开发环境
    kafka spring整合版本匹配
    mac 安装brew
    hadoop2.8.5 idea2019.1.3插件安装
  • 原文地址:https://www.cnblogs.com/lightspeedsmallson/p/4785775.html
Copyright © 2011-2022 走看看