This problem is also stuck for a long time.
Given a string comparison algorithm, there are n strings 22 compared once, ask how many times there will be comparisons.
Because there are many nodes, the tire tree uses the representation of the left son's right brother to save space.
Assuming that the length of the longest public prefix for the two unequal strings is I, the comparison should be 2i+1.
If two strings are equal, the number of comparisons is 2i+2.
You can build the tire tree first, and then the DFS statistic answer, just like in great white books.
1#include <cstdio>2#include <cstring>3 4 Const intMaxnode =4000* ++Ten;5 6 structTire7 {8 intsz;9 intSon[maxnode], Bro[maxnode], Tot[maxnode];Ten CharCh[maxnode]; One Long Longans; A voidClear () {sz =1; son[0] = bro[0] = tot[0] =0; } - - voidInsertChar*s) the { - intU =0, V, n =strlen (s); -tot[0]++; - for(inti =0; I <= N; i++) + { - BOOLFound =false; + for(v = son[u]; v; v =Bro[v]) A if(Ch[v] = = S[i]) {found =true; Break; } at if(!found) - { -v = sz++; -SON[V] =0; -BRO[V] =Son[u]; -Son[u] =v; inTOT[V] =0; -CH[V] =S[i]; to } +U =v; -tot[u]++; the } * } $ Panax Notoginseng voidDfsintDintu) - { the if(Son[u] = =0) {ans + = tot[u] * (tot[u]-1) * D;return; }//leaf node + Long Longsum =0; A for(intv = son[u]; V v =Bro[v]) theSum + = tot[v] * (tot[u)-tot[v]); +Ans + = SUM/2* (d *2+1); - for(intv = son[u]; V v = bro[v]) DFS (d+1, v); $ } $ - Long Longcount () - { theAns =0; -Dfs0,0);Wuyi returnans; the } - }tire; Wu - Const intMAXL = ++Ten; About CharS[MAXL]; $ - intMain () - { - //freopen ("In.txt", "R", stdin); A + intN, Kase =0; the while(SCANF ("%d", &n) = =1&&N) - { $ tire.clear (); the for(inti =0; I < n; i++) {scanf ("%s", s); Tire.insert (s); } theprintf"Case %d:%lld\n", ++Kase, Tire.count ()); the } the - return 0; in}
code June
You can also insert string edge statistics, shorter code and faster. The practice is seen in a blog from the chicory.
1#include <cstdio>2#include <cstring>3 4 Const intMaxnode = +*4000+Ten;5 6 Long Longans;7 8 structTire9 {Ten intSon[maxnode], Bro[maxnode], Tot[maxnode]; One CharCh[maxnode]; A intsz; - voidClear () {sz =1; son[0] = bro[0] = tot[0] =0; } - the voidInsertChar*s) - { - intU =0, V, n =strlen (s); -tot[0]++; + for(inti =0; I <= N; i++) - { + BOOLFound =false; A for(v = son[u]; v; v =Bro[v]) at if(Ch[v] = = S[i]) {found =true; Break; } - if(!found) - { -v = sz++; -SON[V] =0; -BRO[V] =Son[u]; inSon[u] =v; -TOT[V] =0; toCH[V] =S[i]; + } -Ans + = (Tot[u]-1-TOT[V]) * (2* i +1); the if(i = = N) ans + = tot[v] * (2* i +2); *U =v; $tot[u]++;Panax Notoginseng } - } the }tire; + A Const intMAXL = ++Ten; the CharS[MAXL]; + - intMain () $ { $ //freopen ("In.txt", "R", stdin); - - intN, Kase =0; the while(SCANF ("%d", &n) = =1&&N) - {Wuyi tire.clear (); theAns =0; - for(inti =0; I < n; i++) {scanf ("%s", s); Tire.insert (s); } Wuprintf"Case %d:%lld\n", ++Kase, ans); - } About $ return 0; -}
code June
UVa 11732 (Tire tree) "strcmp ()" Anyone?