2015ACM/ICPC亚洲区沈阳站

 

http://acm.split.hdu.edu.cn/showproblem.php?pid=5510

 

 1 //#define txtout
 2 //#define debug
 3 #include<bits/stdc++.h>
 4 #define mt(a,b) memset(a,b,sizeof(a))
 5 using namespace std;
 6 typedef long long LL;
 7 const double pi=acos(-1.0);
 8 const double eps=1e-8;
 9 const int inf=0x3f3f3f3f;
10 const int M=2e3+10;
11 class KMP { ///模式匹配(kmp)O(ls+lp)
12     typedef char typec;///文本元素的类型
13     static const int MV=2e3+10;///字符串的长度
14     int next[MV];
15 public:///匹配串长度 ls,str 存待匹配文本,模式串长度 lp,pat 存模式串
16     int kmp(int ls,typec str[],int lp,typec pat[],int res[]) { ///返回匹配次数,res 中存储每个匹配的初始位置
17         int i=0,j=-1,cnt=0;
18         next[0]=-1;
19         while(i<lp) {
20             if(j==-1||pat[i]==pat[j]) {
21                 next[++i]=++j;
22                 continue;
23             }
24             j=next[j];
25         }
26         i=j=0;
27         while(i<ls) {
28             while(j!=lp&&str[i]==pat[j]) {
29                 i++;
30                 j++;
31             }
32             if(!j) {
33                 i++;
34                 continue;
35             }
36             if(j==lp) {
37                 res[cnt++]=i-j;
38             }
39             j=next[j];
40         }
41         return cnt;
42     }
43 } gx;
44 int n;
45 char a[512][M];
46 int length[512];
47 int res[M];
48 int solve() {
49     if(n==1) return -1;
50     for(int i=0;i<n;i++){
51         length[i]=strlen(a[i]);
52     }
53     int result=-1;
54     for(int i=0,j=1;i<n&&j<n;) {
55         if(gx.kmp(length[j],a[j],length[i],a[i],res)){
56             i++;
57             j=max(j,i+1);
58             continue;
59         }
60         result=j+1;
61         j++;
62     }
63     return result;
64 }
65 int main() {
66 #ifdef txtout
67     freopen("in.txt","r",stdin);
68     freopen("out.txt","w",stdout);
69 #endif // txtout
70     int t,cas=1;
71     scanf("%d",&t);
72     while(t--) {
73         scanf("%d",&n);
74         for(int i=0; i<n; i++) {
75             scanf("%s",a[i]);
76         }
77         printf("Case #%d: %d\n",cas++,solve());
78     }
79     return 0;
80 }
View Code

 

 

end

 

posted @ 2016-09-08 12:25  cs1131  阅读(133)  评论(0编辑  收藏  举报