您的位置:首页 > 其它

Uva-11732-strcmp() Anyone?

2013-03-21 14:19 423 查看
Trie的一道练习题,但是好像不太像普通的实现方式,受教了。

题目要求求出两两相比较的最少值。

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn=4100000;
struct Trie
{
int head[maxn];
int nxt[maxn];
char ch[maxn];
int tot[maxn];
}t;
long long ans,sz;
void insert(char *s)
{
int u=0,v,len=strlen(s);
t.tot[0]++;
for(int i=0;i<=len;i++)
{
bool isFound=false;
for(v=t.head[u];v!=0;v=t.nxt[v])
if(t.ch[v]==s[i])
{
isFound=true;
break;
}
if(!isFound)
{
v=sz++;
t.tot[v]=0;
t.ch[v]=s[i];
t.nxt[v]=t.head[u];
t.head[u]=v;
t.head[v]=0;
}
u=v;
t.tot[u]++;
}
}
void DFS(int u,int depth)
{
if(t.head[u]==0)
ans+=t.tot[u]*(t.tot[u]-1)*depth;
else
{
int sum=0;
for(int v=t.head[u];v!=0;v=t.nxt[v])
sum+=t.tot[v]*(t.tot[u]-t.tot[v]);
ans+=sum/2*(2*depth+1);
for(int v=t.head[u];v!=0;v=t.nxt[v])
DFS(v,depth+1);
}
}
int main()
{
int cas=1,n;
while(scanf("%d",&n)&&n)
{
sz=1;
ans=0;
t.tot[0]=t.head[0]=t.nxt[0]=0;
char str[1001];
while(n--)
{
scanf("%s",str);
insert(str);
}
DFS(0,0);
printf("Case %d: %lld\n",cas++,ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: