字典树 (网易互娱2018笔试题目第4题)

网易互娱笔试第4题,给定一些手机号以及对应的归属地,查询手机号的归属地。

2

3
1357xxxxxxx GuangZhou01
13680xxxxxx GuangZhou01
13799xxxxxx HangZhou02
3
13579246810
13680246810
13799999999
5
3333xxxxxxx nowhere
3334xxxxxxx somewhere
33355555xxx nobody
33355566666 somebody
33366666xxx NULL
10
33333333333
33344444444
33444444444
44444443334
33355566666
33355533355
33366666633
66663336633
33355533341
33338888888

 

#include <bits/stdc++.h>
using namespace std;

#define pb push_back
#define mp make_pair
#define fi first
#define se second
const int Inf=1e9;
#define N 20010
#define M 10  //child :0-9
struct Trie{
    string s;
    int next;  //to next node index,or =-1
}rt[N][M];
int cnt;   //point to index which just used
void Trie_clear(int k){
    for(int i=0;i<M;++i){
        rt[k][i].next=-1;
        rt[k][i].s.clear();
    }
}
void Insert(string &s1,string& s2){
    int k=0;  //point to root node
    for(int i=0;i<(int)s1.length();++i){
        int id=s1[i]-'0';
        if(rt[k][id].next==-1){
            rt[k][id].next=++cnt;
            Trie_clear(cnt);
        }
        if(s1[i+1]=='x'){
            rt[k][id].s=s2;
            break;
        }
        k=rt[k][id].next;
    }
}

string find_val(string &s1){
    int k=0;  //point to root node
    for(int i=0;i<(int)s1.length();++i){
        int id=s1[i]-'0';
        if(rt[k][id].next==-1){
            return "";
        }
        if(rt[k][id].s!=""){
            return rt[k][id].s;
        }
        k=rt[k][id].next;
    }
    return "";
}


int main()
{
    ios::sync_with_stdio(0);
   // freopen("in.txt","r",stdin);
    int T,n,m;
    cin>>T;
    while(T--){
        cin>>n;
        string s1,s2;
        cnt=0;
        Trie_clear(cnt);
        for(int i=0;i<n;++i){
            cin>>s1>>s2;
            s1+='x';
            Insert(s1,s2);
        }
        cin>>m;
        while(m--){
            cin>>s1;
            s1+='x';
            string ans=find_val(s1);
            if(ans=="") cout<<"unknown"<<endl;
            else cout<<ans<<endl;
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值