poj 1159 Palindrome--最长公共子串

/*
	本题主要就是最长公共字串(同他自己的反串)
	所求就是其长度-公共字串的长度
	同时本题用到空间压缩,否则可能内存用超
	我是用的两行的数组,轮流做当前行
*/
#include<stdio.h>
#include<string.h>
char s[5050];
int p[2][5050],n,z;
void dp()
{
	z=0;
	memset(p,0,sizeof(p));
	int i=n-1,j;
	for(;i>=0;i--)
	{
		for(j=1;j<=n;j++)
		{
			if(s[i]==s[j-1])
			{
				p[z][j]=p[(z+1)%2][j-1]+1;
			}
			else 
			{
				if(p[z][j-1]>p[(z+1)%2][j])
					p[z][j]=p[z][j-1];
				else p[z][j]=p[(z+1)%2][j];
			}
		}
		z=(z+1)%2;
	}
	z=(z+1)%2;
	printf("%d\n",n-p[z][n]);
}
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		getchar();
		gets(s);
		dp();
	}
	return 0;
}

 

你可能感兴趣的:(poj 1159 Palindrome--最长公共子串)