poj 2406Power Strings
/*
Name:
Copyright:
Author:
Date: 23/09/11 20:36
Description:
*/
#include <csdio>
#include <cstdlib>
#include <iostream>
#include <stack>
using namespace std;
stack<int> s;
char str[400010];
int next[400010];
void get_next(int n)
{
int i=0,j=-1;
next[0]=-1;
while(i<=n)
{
// puts("dfd");
if(j==-1||str[j]==str[i])
{
i++,j++;
next[i]=j;
}
else
j=next[j];
}
}
int main(int argc, char *argv[])
{
int length;
int n;
while(scanf("%s",str)!=EOF)
{
length=strlen(str);
n=length;
get_next(length);
if(next[length]==n)
{
printf("1 ");
for(int i=2;i<=n;i++)
printf(" %d",i);
}
else if(next[n]==0)
printf("%d",n);
else
{
s.push(n);
int tmp=next[n];
while(tmp>0)
{
//cout<<tmp<<endl;
s.push(tmp);
tmp=next[tmp];
}
printf("%d",s.top());
s.pop();
while(!s.empty())
{
printf(" %d",s.top());
s.pop();
}
}
puts("");
}
system("PAUSE");
return EXIT_SUCCESS;
}/*
Name:
Copyright:
Author:
Date: 23/09/11 21:25
Description:
*/
哎,还是不行,这样的水题,也要将近一个小时。。。
1 。 开始我准备枚举,从头开始往后查找S的后两个字母 ,然后开始朴树匹配,4*10^5,
应该会比较慢的,而且也没用到什么算法 ,放弃了这个思路;
2 。 然后聚了几个例子,发现next【】数组可以应用,但是它只能是答案的倒数第二大的数 ,
后来前next[n]的里面和s的后几位相同,想到用同样的方法在next[n]找答案;