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; }
相关文章推荐
- UVA 11732 strcmp() Anyone? Trie的左儿子右兄弟表示法
- UVA 11732 - strcmp() Anyone? 字典树
- UVa 11732 - strcmp() Anyone? (Trie + 邻接表)
- UVa 11732 strcmp() Anyone?
- 左儿子右兄弟Trie UVA 11732 strcmp() Anyone?
- UVA 11732 - strcmp() Anyone? 字典树
- UVA 11732 "strcmp()" Anyone? Trie树 + 树的左儿子右兄弟存储法
- UVA 11732("strcmp()" Anyone?-Trie与左兄弟右儿子)
- uva_11732_"strcmp()" Anyone?(字典树)
- uva 11732 - strcmp() Anyone?
- UVa 11732 "strcmp()" Anyone? (左儿子右兄弟前缀树Trie)
- UVA 11732 strcmp() Anyone 左兄弟右孩子Trie
- (uva 11732) "strcmp()" Anyone? (trie+左儿子右兄弟表示法)
- UVa 11732 strcmp() Anyone? 求字符串比较次数
- UVA 11732 "strcmp()" Anyone?(字典树)
- uva 11732 - strcmp() Anyone? 不错的Trie题
- UVA11732 strcmp() Anyone?(Trie树)
- UVA 11732 "strcmp()" Anyone?
- uva 11732 strcmp() Anyone? 字典树
- 【UVA】11732 - strcmp() Anyone?