Farmer John has gone out for a walk down the road and thinks he may now be lost! Along the road there are N farms (1≤N≤100) in a row. Farms unfortunately do not have house numbers, making it hard for Farmer John to figure out his location along the road. However, each farm does have a colorful mailbox along the side of the road, so Farmer John hopes that if he looks at the colors of the mailboxes nearest to him, he can uniquely determine where he is.
Each mailbox color is specified by a letter in the range A…Z, so the sequence of N mailboxes down the road can be represented by a string of length N containing letters in the range A…Z. Some mailboxes may have the same colors as other mailboxes. Farmer John wants to know what is the smallest value of K such that if he looks at any sequence of K consecutive mailboxes, he can uniquely determine the location of that sequence along the road.
For example, suppose the sequence of mailboxes along the road is ‘ABCDABC’. Farmer John cannot set K=3, since if he sees ‘ABC’, there are two possible locations along the road where this consecutive set of colors might be. The smallest value of K that works is K=4, since if he looks at any consecutive set of 4 mailboxes, this sequence of colors uniquely determines his position along the road.
Input
The first line of input contains N, and the second line contains a string of N characters, each in the range A…Z.
Output
Print a line containing a single integer, specifying the smallest value of K that solves Farmer John’s problem.
就是求着含有N个大学字母的字符串中,不重复的子序列的最小长度。
比如“ABCDABC”中 子序列长度为2的有"AB" “BC” “CD” “DA” “AB” “BC"虽然没有和DA一样的子序列,但是有和其他三个一样的子序列,所以最小长度不是2;长度为3的有"ABC” “BCD” “CDA” “DAB” “ABC”,在以上四纵序列中ABC有重复的所以长荡湖不是3;子序列长度为4的有“ABCD”“BCDA”“CDAB”“DABC”都不重复,所以最小长度为4
枚举
枚举区间长度,从2一直枚举到n 枚举区间长度为k的所有子序列,然后对子序列一一进行KMP,KMP能寻找原串中与目标串匹配的子序列,得出匹配部分的第一个字母在原串的位置。那么找到匹配后进行计数,计数超过2个则说明原串中有重复的子序列,那么就换k+1的区间。
(写解题报告的时候忽然觉得KMP麻烦了,直接枚举出k区间的所有子串,扔到set里面判重就好了,KMP属实麻烦了)
#include
#include
#include
#include
using namespace std;
bool KMP(string s,string p,int n,int m)
{
int next[105];
next[0]=0;
int j=0;
for(int i=1;i<m;i++)
{
while(j>0 && p[i]!=p[j])
{
j=next[j-1];
}
if(p[i]==p[j])
{
j++;
}
next[i]=j;
}
j=0;
int flag=0;
for(int i=0;i<n;i++)
{
while(j>0 &&p[j]!=s[i])
{
j=next[j-1];
}
if(p[j]==s[i])
{
j++;
}
if(j==m)
{
flag++;
if(flag>=2)
return true;
}
}
return false;
}
int main()
{
int n;
cin>>n;
string str;
cin>>str;
//cout<
for(int k=2;k<=n;k++)
{
bool flag=true;
for(int i=0;i<n-k;i++)
{
string str2(str,i,k);
//string str1(str,0,i);//Ç°
//string s(str,k+i,n-k-i);//ºó
//str1+=s;
if(KMP(str,str2,n,k)==1)
{
flag=false;
break;
}
}
if(flag)
{
cout<<k<<endl;
return 0;
}
}
return 0;
}