首页 > 代码库 > hoj 13830 DNA Sequencing 字典树

hoj 13830 DNA Sequencing 字典树

// 好像没什么好说的了
#include <stdio.h> #include <vector> #include <algorithm> #include <string.h> #include <map> #include <queue> #include <set> #include <math.h> #include <iostream> using namespace std; const int maxn=(int)260020; const int MOD=(int)1e9+7; struct nod{ int num;int height;int ch[26]; void init(){num=height=0;memset(ch,0,sizeof ch);} }; nod trie[maxn]; int cnt=1; const int root=1; void insert(int cur,char s[510],int dig,int num){ // printf("cur %d str: %s cnt:%d\n",cur,s,cnt ); int idx=s[dig]-A;//当前处理的字母 if(trie[cur].ch[idx]==0) trie[cur].ch[idx]=++cnt;//如果未加入那么加入 int ch=trie[cur].ch[idx];// trie[ch].height=dig; if(0==s[dig+1]) trie[ch].num+=num; else insert(ch,s,dig+1,num); } vector<char> q; int dfs(int cur,int h){ int res=0; for(int i=0;i<26;i++){ if(trie[cur].ch[i]!=0){ int ch= trie[cur].ch[i]; // q.push_back((char)(i+‘A‘)); res+=dfs(ch,h); trie[cur].num+=max(trie[ch].num-1,0); // q.erase(q.end()-1,q.end()); } } if(trie[cur].height+1>=h&&trie[cur].num>0 ) { res++; // printf("%d trie[cur].height+1:%d trie[cur].num:%d ",res,trie[cur].height+1,trie[cur].num); // for(int j=0;j<q.size();j++)putchar(q[j]);putchar(‘\n‘); } return res; } void trieprint(int cur,int height){ for(int i=0;i<26;i++){ if(trie[cur].ch[i]!=0){ q.push_back((char)(i+A)); printf("trie[%d] No.%d: Next No.%d height:%d num:%d\n",cur,trie[cur].ch[i],trie[trie[cur].ch[i]].num,trie[cur].height,trie[cur].num); for(int j=0;j<q.size();j++)putchar(q[j]);putchar(\n); trieprint(trie[cur].ch[i],0); q.erase(q.end()-1,q.end()); } } } char s[510]; int main(){ #ifdef shuaishuai freopen("a.txt","r",stdin ); #endif // shuaishuai int n,k,m; while(scanf("%d%d",&n,&k)!=EOF,n+k!=0){ cnt=1; for(int i=0;i<maxn;i++){ trie[i].init(); } for(int i=0;i<n;i++){ scanf("%d%s",&m,s); insert(root,s,0,m); } trie[root].height=-1; // trieprint(root,0); printf("%d\n",dfs(root,k)); } return 0; }

 

hoj 13830 DNA Sequencing 字典树