POJ1451 T9 題解&代碼

第一次寫Trie樹我居然1A了【不,不要算某個PE
Trie樹模板級別的題【哪裏模板了
對於每組數據的dictionary建立一個字典樹,然後dfs查詢,用數組保存離線的一個詢問裏的length-1個輸出

#include<iostream>
#include<stdio.h>
#include<string.h>
#define clr(x) memset(x,0,sizeof(x))
using namespace std;
const int maxl=105;
const int maxn=1005;
int T,n,m,value,tot,Flag[maxl],son[maxl*maxn][27],val[maxl*maxn][27],check[10][4]={
{0,0,0,0},
{0,0,0,0},
{0,1,2,26},
{3,4,5,26},
{6,7,8,26},
{9,10,11,26},
{12,13,14,26},
{15,16,17,18},
{19,20,21,26},
{22,23,24,25}
};
char s[maxl],ans[maxl][maxl],t[maxl],fal[]="MANUALLY";
void newnode(int x,int temp,int v)
{
    //cout<<tot<<' '<<val[x][temp]<<' '<<v<<endl;
    if(v)son[x][temp]=++tot;
    else son[x][temp]=0;
    val[x][temp]=v;
    for(int i=0;i<26;i++)
        son[tot][i]=0,val[tot][i]=0;
}
void Insert(int v)
{
    int len=strlen(s),p=0,x=0,temp;
    while(p!=len)
    {
        temp=s[p]-'a';
        //cout<<temp<<' '<<son[x][temp]<<endl;
        if(son[x][temp])val[x][temp]+=v;
        else newnode(x,temp,v);
        x=son[x][temp];
        p++;
    }
}
void query(int p,int now)
{
    if(p==strlen(s)-1)return;
    for(int i=0;i<4;i++)
        if(son[now][check[s[p]-'0'][i]])
        {
            t[p]=check[s[p]-'0'][i]+'a';
            t[p+1]='\0';
            if((!Flag[p]) || val[now][check[s[p]-'0'][i]]>Flag[p])
            {
                Flag[p]=val[now][check[s[p]-'0'][i]],strcpy(ans[p],t);
                //printf("%d %d %s\n",p,val[now][check[s[p]-'0'][i]],ans[p]);
            }
            query(p+1,son[now][check[s[p]-'0'][i]]);
        }
}
int main(void)
{
    scanf("%d",&T);
    for(int i=1;i<=T;i++)
    {
        printf("Scenario #%d:\n",i);
        tot=0;
        newnode(0,0,0);
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%s%d",s,&value);
            Insert(value);
        }
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%s",s);
            clr(Flag);
            query(0,0);
            int len=strlen(s);
            for(int i=0;i<len-1;i++)
                if(Flag[i])printf("%s\n",ans[i]);
                else printf("%s\n",fal);
            printf("\n");
        }
        printf("\n");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章