hdoj5510Bazinga【strstr+并查集】

来源:互联网 发布:网络药品经营许可证 编辑:程序博客网 时间:2024/05/17 13:12

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 (1in) such that there exists an integer j (1j<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 (1t50) which is the number of test cases.
For each test case, the first line is the positive integer n (1n500) 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
45ababczabcabcdzabcd4youlovinyouaboutlovinyouallaboutlovinyou5dedefabcdabcdeabcdef3abaccc
 

Sample Output
Case #1: 4Case #2: -1Case #3: 4Case #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;}


0 0
原创粉丝点击