bzoj_3012_[usaco2012 Dec]first!_trie tree + topological sorting
Test instructions
Given n of different strings with a total length of not more than M, you can now arbitrarily specify the size relationship between the characters. Ask how many strings might be the smallest strings in the dictionary order and output those strings. N <= 30,000, m <= 300,000 analysis: First regardless of the size of the relationship, if a string is another string prefix, then the other string must not be a dictionary order the smallest string, we can use the trie tree is a good solution. Consider the same prefix, the string after the prefix of the character should be the same prefix with the string after the prefix of the character has a clear size relationship, according to the size of the relationship between the edge, we use topological sorting to determine whether the contradiction. All of the above can be the smallest string in the dictionary order. Code:
1#include <stdio.h>2#include <string.h>3#include <algorithm>4#include <queue>5 using namespacestd;6 #defineN 300507 structA8 {9 intson[ -],end;Ten}t[n*Ten]; One intn,tot,head[ -],to[n],nxt[n],c[ -],cnt=1, ans[30010]; A Chars[30010][310]; - voidAddintUintv) - { theto[++cnt]=v; -nxt[cnt]=Head[u]; -head[u]=CNT; -c[v]++; + } - voidInsertintx) + { A intp=1; at intLen=strlen (s[x]+1); - for(intI=1; i<=len;i++) - { - intid=s[x][i]-'a'+1; - if(!t[p].son[id]) t[p].son[id]=++CNT; -p=T[p].son[id]; in } -T[p].end=1; to } + BOOLSearchintx) - { the intp=1; * intLen=strlen (s[x]+1); $ for(intI=1; i<=len;i++)Panax Notoginseng { - if(T[p].end)return 0; the intid=s[x][i]-'a'+1; + for(intj=1; j<= -; j + +) A { the if(j!=id&&T[p].son[j]) + { - Add (id,j); $ } $ } -p=T[p].son[id]; - } the return 1; - }Wuyi BOOLTopsort () the { -Queue <int>Q; Wu for(intI=1; i<= -; i++)if(c[i]==0) Q.push (i); - while(!q.empty ()) About { $ intx=Q.front (); Q.pop (); - for(intI=head[x];i;i=Nxt[i]) - { -c[to[i]]--; A if(c[to[i]]==0) Q.push (To[i]); + } the } - for(intI=1; i<= -; i++)if(C[i])return 0; $ return 1; the } the intMain () the { thescanf"%d",&n); - for(intI=1; i<=n;i++) in { thescanf"%s", s[i]+1); the Insert (i); About } the for(intI=1; i<=n;i++) the { theMemset (Head,0,sizeof(head)); +Memset (c,0,sizeof(c)); Cnt=0; - if(!search (i))Continue; the if(!topsort ())Continue;Bayians[++tot]=i; the } theprintf"%d\n", tot); - for(intI=1; i<=tot;i++) - { theprintf"%s\n", s[ans[i]]+1); the } the}
bzoj_3012_[usaco2012 Dec]first!_trie tree + topological sorting