uva 11732 "strcmp()" Anyone?
程序员文章站
2022-03-02 14:10:36
...
思路:
将所有单词记入trie中,再查找。
注意:
1、用 long long 。
2、在插入时,应在字符串后多插入一个\0,不然 "there" 和 "the" 这种会有问题。
代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <cstring>
#include <map>
using namespace std;
#define maxn 4000
#define maxm 1000
#define maxnode maxm*maxn
int n;
struct Trie{
int head[maxnode+5];
int next[maxnode+5];
char ch[maxnode+5];
int sum[maxnode+5];
int sz;
long long ans;
void clear(){
memset(head,0,sizeof(head));
memset(next,0,sizeof(next));
memset(ch,0,sizeof(ch));
memset(sum,0,sizeof(sum));
sz=1,ans=0;
}
void insert(char* s){
long long y=0;
int u=0,Size=strlen(s);
sum[0]++;
for(int i=0;i<=Size;i++){
bool flag=false;
char x=s[i];
int j;
for(j=head[u];j;j=next[j]){
if(ch[j]==x) {
flag=true;
break;
}
}
if(flag==false){
ch[++sz]=x;
next[sz]=head[u];
head[u]=sz;
j=sz;
}
u=j,sum[u]++;
}
ans+=y;
}
long long cnt(int d,int u){
if(head[u]==0) return ans=ans+sum[u]*(sum[u]-1)*d;
long long s=0;
for(int i=head[u];i;i=next[i]){
s+=sum[i]*(sum[u]-sum[i]);
}
s=s/2*(2*d+1);
ans+=s;
for(int i=head[u];i;i=next[i]){
cnt(d+1,i);
}
return ans;
}
};
Trie trie;
int main() {
int T=0;
while(~scanf("%d",&n)&&n!=0){
trie.clear();
char s[maxm+5];
for(int i=1;i<=n;i++){
scanf("%s",s);
trie.insert(s);
}
printf("Case %d: %lld\n",++T,trie.cnt(0,0));
}
return 0;
}
上一篇: 解决mysql的死锁
下一篇: 死锁的产生与解决
推荐阅读
-
UVA 11732 strcmp() Anyone? strcmp()函数(Trie)
-
字典树("strcmp()" Anyone? uva11732)
-
"Strcmp()" Anyone? UVA - 11732
-
UVA11732 "strcmp()" Anyone?
-
UVA11732 "strcmp()" Anyone?
-
UVa 11732-strcmp() Anyone?
-
Trie UVA 11732 "strcmp()" Anyone?
-
【uva11732】"strcmp()" Anyone?
-
UVA11732 “strcmp()“ Anyone?
-
UVa 11732 strcmp() Anyone?