Ladies and gentlemen, please sit up straight.
Don’t tilt your head. I’m serious.
For n given strings S 1 , S 2 , · · · , S n , 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 S j is not a substring of S i .
A substring of a string S i is another string that occurs in S i . 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
S 1 , S 2 , · · · , S n . 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
题意:就是找子串,找出最大的字符串的标号,使得前面所有的字符串至少有一个不是该字符的子串,如果不存在,输出-1
思路:尽可能简化,加一个预处理,判断相邻两个字符串是否为从属关系,在计算中,如果前面都是该字符的子串,则可继续判断ans的最大值。
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cstdio>
#include <string>
#include <stack>
#include <deque>
using namespace std;
#define MAX 0x3f3f3f
typedef long long ll;
int main()
{
ll T,n,i,j,ans;
cin>>T;
string s[505];
ll e=1;
ll flag[505];
while(T--)
{
cin>>n;
for(i=1;i<=n;i++)
cin>>s[i];
ll f=0;
memset(flag,0,sizeof(flag));
for(i=1;i<n;i++)
{
if(s[i+1].find(s[i])!=-1)
{
flag[i]=1;
f++;
}
}
if(f==n-1)//判断是否都是子串的情况
{
cout<<"Case #"<<e++<<": ";
cout<<"-1"<<endl;
continue;
}
ans=-1;
for(i=2;i<=n;i++)
{
if(ans!=i-1&&flag[i-1]==1)//前面的都是该字符的子串
continue;
else//计算ans的最大值
{
for(j=1;j<i;j++)
{
if(s[i].find(s[j])==-1)
ans=i;
}
}
}
cout<<"Case #"<<e++<<": "<<ans<<endl;;
}
return 0;
}