您的位置:首页 > 其它

hdoj5510Bazinga【strstr+并查集】

2016-01-28 18:10 429 查看


Bazinga

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

Total Submission(s): 1438    Accepted Submission(s): 444


Problem Description

Ladies and gentlemen, please sit up straight.
Don't tilt your head. I'm serious.



For n given
strings S1,S2,⋯,Sn,
labelled from 1 to n,
you should find the largest i (1≤i≤n) such
that there exists an integer j (1≤j<i) and Sj is
not a substring of Si.

A substring of a string Si is
another string that occurs in Si.
For example, ``ruiz" is a substring of ``ruizhang", and ``rzhang" is not a substring of ``ruizhang".

 

Input

The first line contains an integer t (1≤t≤50) which
is the number of test cases.

For each test case, the first line is the positive integer n (1≤n≤500) and
in the following n lines
list are the strings S1,S2,⋯,Sn.

All strings are given in lower-case letters and strings are no longer than 2000 letters.

 

Output

For each test case, output the largest label you get. If it does not exist, output −1.

 

Sample Input

4
5
ab
abc
zabc
abcd
zabcd
4
you
lovinyou
aboutlovinyou
allaboutlovinyou
5
de
def
abcd
abcde
abcdef
3
a
ba
ccc

 

Sample Output

Case #1: 4
Case #2: -1
Case #3: 4
Case #4: 3

 

Source

2015ACM/ICPC亚洲区沈阳站-重现赛(感谢东北大学)

 

刚做这道题时看别人给的一个思路是strstr以为很简单然后就用strstr暴力果断超时然后想到一个如果a是b的子串b是c的子串那么只需判断c和b即可然后想依靠这种思路优化。但不知道怎么实现。刚开始想的用vector存然后写出来超时。然后又用数组还是超时。最后猛然想到用并查集试试本来不报什么希望结果交了一发AC。

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<list>
#include<queue>
using namespace std;
int father[510];
char str[510][2010];
int find(int x){
return x==father[x]?x:father[x]=find(father[x]);
}
int main()
{
int n,i,j,k=1,t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
for(i=1;i<=n;++i){
father[i]=i;
}
int ans=-1;
for(i=1;i<=n;++i){
scanf("%s",str[i]);
for(j=i-1;j>=1;--j){
int a=find(i),b=find(j);
if(a==b)continue;
else if(strstr(str[i],str[j])){
father[i]=j;
}
else {
ans=i;
break;
}
}
}
printf("Case #%d: %d\n",k++,ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdoj5510Bazingastrst