Trie to determine whether the prefix code

Prefix code: if a code is not a prefix of another code, for the prefix code.

Given several strings to determine whether the prefix encoding.
Direct string match.

template

#include<bits/stdc++.h>
using namespace std;
#define maxn 100005
  
int ch[maxn][15];
int val[maxn];
int sz;
char str[20];
int num[maxn];
int t;
int len;
  
bool setup(char*s)
{
    bool ok=true;
    int u=0,n=strlen(s);
    for(int i=0; i<n; i++)
    {
        int id=s[i]-'0';
        if(ch[u][id]==0)
        {
            ch[u][id]=++sz;
            memset(ch[sz],0,sizeof(ch[sz]));
            val[sz]=0;
        }
        u=ch[u][id];
        if(val[u]>0)
        {
            ok=false;
            break;
        }
    }
    val[u]++;
    if(ok)
    {
        for(int i=0; i<=9; i++)
            if(ch[u][i]!=0)
            {
                ok=false;
                break;
            }
    }
    return ok;
}
  
int main()
{
    scanf("%d",&t);
    int cas=1;
    while(t--)
    {
        bool ok=true;
        scanf("%d",&len);
        memset(ch,0,sizeof(ch));
        sz=0;
        for(int i=1; i<=len; i++)
        {
            scanf("%s",str);
  
            if(ok)
                ok=setup(str);
        }
        printf("Case #%d: ",cas);
        if(ok)
            printf("Yes\n");
        else
            printf("No\n");
        cas++;
    }
    return 0;
}
Published 313 original articles · won praise 105 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43460224/article/details/104346566