poj3630 || hdoj1671 (trie)

Topic link: https: //vjudge.net/problem/HDU-1671

The meaning of problems: Given n string, determines whether or not there are some other string is a prefix string.

Ideas:

  Sets of templates, there is a prefix may be two situations:

    Before the current string string already exists when enumerating the digits; (i.e. 911 already exists, the current insertion 9112)

      After completion string or the current enumeration, as well as the child node of the node. (Ie 9112 already exists, the current insertion 911)

AC code:

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

const int maxn=1e6+5;
int T,n,trie[maxn][12],key[maxn],cnt;
int flag;
char str[12];

void insert(char *s){
    int len=strlen(s),u=0;
    for(int i=0;i<len;++i){
        int t=s[i]-'0';
        if(!trie[u][t]){
            ++cnt;
            memset(trie[cnt],0,sizeof(trie[cnt]));
            key[cnt]=0;
            trie[u][t]=cnt;
        }
        if(key[trie[u][t]]){
            flag=0;
            return;
        }
        u=trie[u][t];
        if(i==len-1) key[u]=1;
    }
    for(int i=0;i<10;++i)
        if(trie[u][i]){
            flag=0;
            break;
        }
}

int main(){
    scanf("%d",&T);
    while(T--){
        scanf("%d",&n);
        memset(trie[0],0,sizeof(trie[0]));
        flag=1,cnt=0;
        for(int i=0;i<n;++i){
            scanf("%s",str);
            if(flag) insert(str);
        }
        if(flag) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/FrankChen831X/p/11829478.html