hihoCoder#1107 : Shortest Proper Prefix (前缀树)

题目大意:在n个单词中,如果以s作为前缀的单词个数不超过5个,那么称s为proper prefix。如果s为proper prefix并且s的任何一个前缀(不包括s)都不是proper prefix,那么称s为shortest proper prefix,找出词典中shortest proper prefix的个数。

题目分析:建立一棵trie,在trie上深搜即可。

代码如下:

# include<iostream>
# include<cstdio>
# include<cstring>
# include<vector>
# include<queue>
# include<list>
# include<set>
# include<map>
# include<string>
# include<cmath>
# include<cstdlib>
# include<algorithm>
using namespace std;
# define LL long long const int N=1005;
const int INF=1000000000;
const LL oo=0x7fffffffffffffff;
const double eps=1e-10; struct Node
{
int u,l;
Node(){}
Node(int _u,int _l):u(_u),l(_l){}
};
int cnt,n;
int size[N*N<<1];
int tr[N*N<<1][26]; void init()
{
cnt=1;
memset(tr,0,sizeof(tr));
memset(size,0,sizeof(size));
} void insert(string p)
{
int len=p.size();
int u=0;
for(int i=0;i<len;++i){
int c=p[i]-'a';
if(!tr[u][c]) tr[u][c]=cnt++;
u=tr[u][c];
++size[u];
}
} void dfs(int u,int &ans)
{
if(u>0&&size[u]<=5){
++ans;
}else{
for(int i=0;i<26;++i)
if(tr[u][i]) dfs(tr[u][i],ans);
}
} int solve()
{
int ans=0;
dfs(0,ans);
return ans;
} int main()
{
string p;
while(~scanf("%d",&n))
{
init();
while(n--)
{
cin>>p;
insert(p);
}
printf("%d\n",solve());
}
return 0;
}

  

上一篇:C#webform LinQ


下一篇:C Programming vs. Java Programming