字典树判断是否为前缀编码

前缀编码:如果一个编码不是另一个编码的前缀,则为前缀编码。

给定几个字符串,判断是否是前缀编码。
直接字符串匹配。

模板

#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;
}
发布了313 篇原创文章 · 获赞 105 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43460224/article/details/104346566