Spy

Spy

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 771    Accepted Submission(s): 370


Problem Description
“Be subtle! Be subtle! And use your spies for every kind of business. ”
— Sun Tzu
“A spy with insufficient ability really sucks”
— An anonymous general who lost the war
You, a general, following Sun Tzu’s instruction, make heavy use of spies and agents to gain information secretly in order to win the war (and return home to get married, what a flag you set up). However, the so-called “secret message” brought back by your spy, is in fact encrypted, forcing yourself into making deep study of message encryption employed by your enemy.
Finally you found how your enemy encrypts message. The original message, namely s, consists of lowercase Latin alphabets. Then the following steps would be taken:
* Step 1: Let r = s
* Step 2: Remove r’s suffix (may be empty) whose length is less than length of s and append s to r. More precisely, firstly donate r[1...n], s[1...m], then an integer i is chosen, satisfying i ≤ n, n - i < m, and we make our new r = r[1...i] + s[1...m]. This step might be taken for several times or not be taken at all.
What your spy brought back is the encrypted message r, you should solve for the minimal possible length of s (which is enough for your tactical actions).
 

Input
There are several test cases.
For each test case there is a single line containing only one string r (The length of r does not exceed 105). You may assume that the input contains no more than 2 × 106 characters.
Input is terminated by EOF.
 

Output
For each test case, output one line “Case X: Y” where X is the test case number (starting from 1) and Y is the desired answer.
 

Sample Input
abc aab abcadabcabcad aaabbbaaaabbbaa abcababcd
 

Sample Output
Case 1: 3 Case 2: 2 Case 3: 5 Case 4: 6 Case 5: 4
 

Source
 

Recommend
liuyiding   |   We have carefully selected several similar problems for you:  6216 6215 6214 6213 6212 

題意:求s的一個子串t的最小長度,子串t的前綴+........+前綴 +子串t 構成母串s

思路:先用最短的子串匹配,若匹配不成功,在慢慢的爲子串更新用KMP,當不能匹配的時候,就從上一個匹配完成的位置開始把剩下的那段加到子串t中。 

代碼如下:
#include<iostream>
#include<stdio.h>
#include<string.h>

using namespace std;
const int N=2*1e6+5;
char s[N],t[N];
int next_s[N];

int kmp()
{
	int i=0,j=-1,len=strlen(s),last=0,y=-1,m=0,k;
	next_s[0]=-1;
	while(i<len)
	{
		if(j==-1)
		{
			for(k=last;k<=i;k++)
			{
				t[m]=s[k];
				while(y!=-1&&t[m]!=t[y])
					y=next_s[y];
				next_s[++m]=++y;
			} 
			j=m;
			i++;
		}
		else if(s[i]==t[j])
			i++,j++;
		else
			j=next_s[j];	
		if(j>=m)//匹配超出t串重新匹配 ,並記錄匹配位置 
		{
			j=0;
			last=i;
		}
	}
	return len-(last-m);
}
int main()
{
	int count=1;
	while(~scanf("%s",s))
	{
		int ans=kmp();
		printf("Case %d: %d\n",count++,ans);
	}
	return 0;
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章