字典樹+Codeforces1285D

字典樹模板

// 字典樹模板
#include <bits/stdc++.h>
using namespace std;
struct{
    int num; // 如該節點是一個單詞的結尾,記錄單詞的編號
    int next[26];
}trie[1000001];
string s[100001],a;
int tot,ans;
void Insert(string c,int k)
{
    // 插入一個字符串
    int i,t,len,p=1; // p表示標號
    len = c.length(); // 獲取字符串的長度
    for(i = 0;i<len;i++) // 遍歷
    {
        t=c[i]-'a'; // 字母的ascii
        if(trie[p].next[t] ==0) // 說明沒有對應的節點
        {
            tot++; // 新增編號爲tot的節點
            trie[p].next[t] = tot;// 記下p孩子節點的編號
            p = trie[p].next[t]; // p 指向新添加的節點,一步迭代
        }
        else
        {
            p=trie[p].next[t]; // 若已經存在,再令p指向它
        }
    }
    trie[p].num=k; // for循環執行完,證明第k個單詞已經加入
}
int Find(string c) // 查找其中是否有字符串
{
    int i,t,len,p=1;
    len = c.length();
    for(i = 0;i<len;i++)
    {
        t = c[i]-'a';
        if(trie[p].next[t] ==0) return 0; // 沒有要找的字符
        p=trie[p].next[t]; // 若存在繼續查找
    }
    return trie[p].num;
}
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        cin>>s[i]>>a;
        Insert(a,i);
    }
    for(int i=1;i<=m;i++)
    {
        cin>>a;
        ans=Find(a);
        if(ans)     cout<<s[ans]<<endl;
        else    cout<<"None"<<endl; // 沒找到
    }
    return 0;
}

藍書代碼:主要是迭代部分

int trie[SIZE][26],tot=1;
void Insert(char * str)
{
    int len = strlen(str),p=1;
    for(int k=0;k<len;k++)
    {
        int ch = str[k]-'a';
        if(trie[p][ch]==0)  trie[p][ch] =++tot;
        p=trie[p][ch];
    }
    End[p] = true; // 該節點是終點
}
bool Search(char *str)
{
    int len = strlen(str),p=1;
    for(int k=0;k<len;k++)
    {
        p=trie[p][str[k]-'a'];
        if(p==0) return false;
    }
    return End[p];
}

CF1285D
題意:題意:給定n個數,要求你設定一個X,這個X與每個數異或後所得的結果最小,並且這個X要儘可能的大,輸出這個異或出的最小的結果


#include <bits/stdc++.h>
using namespace std;
int cnt=1;
int tri[1<<21][2];
void Insert(int x)
{
    int p=1;
    for(int i=29;i>=0;i--) // 一共三十位
    {
        int ch =(x>>i)&1; // 取出二進制最高位
        if(tri[p][ch]==0) // p 是節點
        {
            tri[p][ch]=++cnt; // 統計個數
        }
        p=tri[p][ch];
    }
}
int solve(int mode,int now)
{
    if(mode==-1) // 小於0了返回0
        return 0;
    if(tri[now][0]==0)
        return solve(mode-1,tri[now][1]); // 選擇最小ans值所以選擇已有的
    else
    if(tri[now][1]==0)
        return solve(mode-1,tri[now][0]);
    else
        return ((1<<mode )+ min(solve(mode-1,tri[now][1]),solve(mode-1,tri[now][0]) )); // 因爲要保證X是最大的,所以在最高有效位要留一個1才行
}
int main()
{
    int n,a;
    cin>>n;
    while(n--)
    {
        cin>>a;
        Insert(a);
    }
    cout<<solve(29,1)<<endl;
    //return "BT7274", NULL;
}
發佈了57 篇原創文章 · 獲贊 3 · 訪問量 2909
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章