Shortest Prefixes UVALive - 3046 (字典树)

传送门

题意:找出每个单词具有认证功能的前缀

题解:使用字典树,我使用的这个除了要注意在clear时每次将val也得初始化一下,不然下一组永远在这组基础上再往上走

附上代码:


#include<bits/stdc++.h>

using namespace std;

const int maxnode=2e4+50;
const int sigma_size=26;
const int maxn=1e3+50;

struct Trie{
    int ch[maxnode][sigma_size];
    int val[maxnode];
    int sz;
    void clear(){
        sz=1;
        memset(ch[0],0,sizeof(ch[0]));
        memset(val,0,sizeof(val));
    }
    int idx(char c){
        return c-'a';
    }
    void insert(string s){
        int u=0,n=s.size();
        for(int i=0;i<n;i++){
            int c=idx(s[i]);
            if(!ch[u][c]){
                memset(ch[sz],0,sizeof(ch[sz]));
                ch[u][c]=sz++;
            }
            u=ch[u][c];
            val[u]++;
        }
    }
    string find_prefixes(string s,int len){
        int u=0;
        string ans="";
        for(int i=0;i<len;i++){
            ans+=s[i];
            int c=idx(s[i]);
            u=ch[u][c];
            if(val[u]==1){
                break;
            }
        }
        return ans;
    }
};
Trie trie;

int main()
{
    int t;
    string s[1050];

    cin >> t;
    getline(cin, s[0]);
    getline(cin, s[0]);
    while (t--) {
        trie.clear();

        int tot = 0;
        while (getline(cin, s[tot]) && s[tot][0])
            trie.insert(s[tot++]);

        for (int i = 0; i < tot; i++) {
            string ans=trie.find_prefixes(s[i],s[i].size());
            cout<<s[i]<<" "<<ans<<endl;
        }

        if(t)
            cout << endl;
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/zhouzi2018/article/details/83685273