题目链接
http://hihocoder.com/problemset/problem/1107?sid=1355923
题意
要求输入n个字符串,寻找有多少个最短合适子串。
合适子串:最多有5个串以该串为前缀
最短合适子串:s去掉最后一个字符后,就不是合适子串了。
注意:""也要看作一个字符,也就是说ab,ac,ad,ae中的a并不满足条件。但是ab,ac,ad,ae,af,ag中的a就满足条件。
题解
先全部读入进来,建立一棵trie树,用cnt数组标志每个节点被经过的次数。然后利用DFS,求出当前节点cnt值<=5,但它的父亲节点值>5的节点。对应最短合适子串的概念。
一个注意点就是cnt[0]在一个子串进来的时候也要+1,因为""也是一个字符。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define INIT(x) memset(x,0,sizeof(x))
#define eps 1e-8
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 1000005;
int trie[maxn][26],ans;
int cnt[maxn];
int k = 1;
void insert (char *w) {
int len = strlen(w);
int p = 0;
cnt[0]++; //例如ab,ac,ad,ae,af,ag,由于a是记录在边上,而不是点上,所以要cnt[0]++
for(int i=0;i<len;i++) {
int c = w[i]-'a';
if(!trie[p][c]) {
trie[p][c] = k;
k++;
}
p = trie[p][c];
cnt[p]++;
}
}
void dfs(int x,int father) {
if(x&&cnt[x]<=5&&cnt[father]>5)
ans++;
else for(int i=0;i<26;i++) {
if(trie[x][i]) {
dfs(trie[x][i],x);
}
}
}
int n;
char s[maxn];
int main()
{
while(cin>>n)
{
INIT(trie);
INIT(cnt);
ans = 0;
k = 1;
for(int i=0;i<n;i++) {
scanf("%s",s);
insert(s);
}
dfs(0,-1);
cout<<ans<<endl;
}
}