The Dominator of Strings
Time Limit: 3000/3000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total Submission(s): 2694 Accepted Submission(s): 975
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.
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
题意:给定一系列的字符串,让找出一个字符串,可以包含其他所有的字符串。
思路:找出最长的那个字符串,对它进行hash,它一定是可能满足条件的,如果对于最长的长度有多个字符串,如果存在满足条件的字符串,那么这几个等长的字符串一定相同。对于其他的字符串,判断最长的字符串中是否含有其他字符串就行了。(用最原始的暴力就能过, 可能是因为没有大的数据)。
代码:
#include <stdio.h>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include<queue>
#include<iostream>
#include<list>
using namespace std;
typedef unsigned long long ull;
const int N = 1e5+5;
const int X = 163;
ull hhash[N], p[N];
char str[N];
char temp[N];
ull value[N];
int length[N];
int m;
void inIt() {
p[0] = 1;
for(int i = 1; i <= N - 5; i++)
p[i] = p[i-1] * X;
}
ull get(int l, int r, ull g[]) {
return g[r] - g[l-1]*p[r-l+1];
}
int main() {
inIt();
int t, index, Max, flag, len;
ull sum;
scanf("%d", &t);
while(t--) {
scanf("%d", &m);
Max = 0;
for(int i = 1; i <= m; i++) {
scanf("%s", str);
len = strlen(str);
if(len > Max) {
Max = len;
strcpy(temp, str);
}
sum = 0;
for(int j = 1; j <= len; j++)
sum = sum * X + (str[j-1] - 'a');
value[i] = sum;
length[i] = len;
}
hhash[0] = 0;
for(int i = 1; i <= Max; i++) {
hhash[i] = hhash[i-1]*X + (temp[i-1] - 'a');
}
for(int i = 1; i <= m; i++) {
flag = 0;
len = length[i];
for(int k = 1; k <= Max-len+1; k++) {
if(value[i] == get(k, k+len-1, hhash)) {
flag = 1;
break;
}
}
if(!flag) {
break;
}
}
if(flag) {
printf("%s\n", temp);
}
else
printf("No\n");
}
return 0;
}