The Dominator of Strings
Problem Description
Here you have a set of strings. A dominator is a string of the set dominating all strings else. The string S is dominated by T if S is a substring of T.
Input
The input contains several test cases and the first line provides the total number of cases.
For each test case, the first line contains an integer N indicating the size of the set.
Each of the following N lines describes a string of the set in lowercase.
The total length of strings in each case has the limit of 100000.
The limit is 30MB for the input file.
Output
For each test case, output a dominator if exist, or No if not.
Sample Input
3
10
you
better
worse
richer
poorer
sickness
health
death
faithfulness
youbemyweddedwifebetterworsericherpoorersicknesshealthtilldeathdouspartandpledgeyoumyfaithfulness
5
abc
cde
abcde
abcde
bcde
3
aaaaa
aaaab
aaaac
Sample Output
youbemyweddedwifebetterworsericherpoorersicknesshealthtilldeathdouspartandpledgeyoumyfaithfulness
abcde
No
Source
输入输出测试
本题思路:通过kmp方法寻找子串,长度最长的那个串作为主串,判断其余各串是不是模式串。
方法一:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#define Maxn 450000
using namespace std;
struct data
{
string s;
int len;
}p[Maxn];
int nex[100005];
void getnex(string b)
{
int i=0,j=-1;
nex[0]=-1;
int m=b.size();
while(i<m)
{
if(j==-1 || b[i]==b[j])nex[++i]=++j;
else j=nex[j];
}
}
bool KMP(string a,string b)
{
getnex(b);
int i=0,j=0;
int n=a.size(),m=b.size();
while(i<n)
{
if(j==-1 || a[i]==b[j])
{
i++;j++;
}
else j=nex[j];
if(j>=m)
return 1;
}
return 0;
}
string sz;
int main()
{
cin.sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int len = 0;
for(int i=0;i<n;i++)
{
cin>>p[i].s;
if(p[i].s.length() > len)
{
len = p[i].s.length();
sz = p[i].s;
}
}
int flag = 0;
for(int i=0;i<n;i++)
{
if(!KMP(sz, p[i].s))
{
flag = 1;
break;
}
}
if(flag) cout << "No" << endl;
else cout << sz << endl;
}
return 0;
}
方法二:
通过定义string类来储存大数据。通过string中含有的函find()寻找子串。//因为string可以根据串的大小来扩展空间。
#include <iostream>
#include<cstdio>
#include<string>
using namespace std;
string s[100005];
int main()
{
int t;
cin.sync_with_stdio(false);
cin>>t;
while(t--)
{
int n;
cin>>n;
int num=0;
string p;
for(int i=0;i<n;i++)
{
cin>>s[i];
if(num<s[i].size())
{
num=s[i].size();
p=s[i];
}
}
int f=1;
for(int i=0;i<n;i++)
{
if(p==s[i])continue;
int k=p.find(s[i]);
if(k>p.size())
{
f=0;
break;
}
}
if(f)cout<<p<<endl;
else cout<<"No"<<endl;
}
return 0;
}