Trie 树的一些题

Trie 树的一些题

牛客练习赛11 假的字符串 (Trie树+拓扑找环)

链接:https://ac.nowcoder.com/acm/problem/15049
来源:牛客网

给定n个字符串,互不相等,你可以任意指定字符之间的大小关系(即重定义字典序),求有多少个串可能成为字典序最小的串,并输出它们

题解:对于第i个字符串来说,如果有一个串是他的前缀,那么这个前缀的字典序重定义后是肯定比他小的,所以我们用trie树保存前缀

​ 对于当前字符串,从该字符串的第i个字母向其父亲节点上的其他字母连边,表示存在大小关系\(str[i]>str[others]\) 这样就指定了 第i个字母的与其他字母的大小关系了,如果当前关系成立的话,就不会出现a>b>a这样的情况 即不会出现环的情况,所以我们用拓扑排序判断是否有环即可

/**
 *        ┏┓    ┏┓
 *        ┏┛┗━━━━━━━┛┗━━━┓
 *        ┃       ┃  
 *        ┃   ━    ┃
 *        ┃ >   < ┃
 *        ┃       ┃
 *        ┃... ⌒ ...  ┃
 *        ┃       ┃
 *        ┗━┓   ┏━┛
 *          ┃   ┃ Code is far away from bug with the animal protecting          
 *          ┃   ┃   神兽保佑,代码无bug
 *          ┃   ┃           
 *          ┃   ┃        
 *          ┃   ┃
 *          ┃   ┃           
 *          ┃   ┗━━━┓
 *          ┃       ┣┓
 *          ┃       ┏┛
 *          ┗┓┓┏━┳┓┏┛
 *           ┃┫┫ ┃┫┫
 *           ┗┻┛ ┗┻┛
 */
// warm heart, wagging tail,and a smile just for you!
//
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                           O\  =  /O
//                        ____/`---'\____
//                      .'  \|     |//  `.
//                     /  \|||  :  |||//  \
//                    /  _||||| -:- |||||-  \
//                    |   | \  -  /// |   |
//                    | \_|  ''\---/''  |   |
//                    \  .-\__  `-`  ___/-. /
//                  ___`. .'  /--.--\  `. . __
//               ."" '<  `.___\_<|>_/___.'  >'"".
//              | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//              \  \ `-.   \_ __\ /__ _/   .-` /  /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                     佛祖保佑      永无BUG
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef unsigned long long uLL;
#define ls rt<<1
#define rs rt<<1|1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define bug printf("*********\n")
#define FIN freopen("input.txt","r",stdin);
#define FON freopen("output.txt","w+",stdout);
#define IO ios::sync_with_stdio(false),cin.tie(0)
#define debug1(x) cout<<"["<<#x<<" "<<(x)<<"]\n"
#define debug2(x,y) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<"]\n"
#define debug3(x,y,z) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<" "<<#z<<" "<<z<<"]\n"
const int maxn = 2e5 + 5 + 3e4;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double Pi = acos(-1);
LL gcd(LL a, LL b) {
    return b ? gcd(b, a % b) : a;
}
LL lcm(LL a, LL b) {
    return a / gcd(a, b) * b;
}
double dpow(double a, LL b) {
    double ans = 1.0;
    while(b) {
        if(b % 2)ans = ans * a;
        a = a * a;
        b /= 2;
    } return ans;
}
LL quick_pow(LL x, LL y) {
    LL ans = 1;
    while(y) {
        if(y & 1) {
            ans = ans * x % mod;
        } x = x * x % mod;
        y >>= 1;
    } return ans;
}


int du[27];
int mp[27][27];
int tuop() {
    queue<int> qu;
    while(!qu.empty()) qu.pop();
    memset(du, 0, sizeof(du));
    for(int i = 0; i < 26; ++i) {
        for(int j = 0; j < 26; ++j) {
            if(mp[i][j] == 1) du[j]++;
        }
    }
    for(int i = 0; i < 26; ++i) {
        if(du[i] == 0) qu.push(i);
    }
    int num = 0;
    while(!qu.empty()) {
        int u = qu.front();
        qu.pop();
        num++;
        for(int i = 0; i < 26; ++i) {
            if(mp[u][i] == 1) {
                du[i]--;
                if(du[i] == 0) qu.push(i);
            }
        }
    }
    return num;
}
const int maxChild = 26;
const int maxNode = maxn;
int tot = 0;
int child[maxNode | 10][maxChild];
//int cnt; //该结点后缀的数量
int isWord[maxNode];
void insert(string s) {
    int pos, cur = 0;
    for (int i = 0; i < s.length(); ++i) {
        pos = s[i] - 'a';
        if (child[cur][pos] == 0)
            child[cur][pos] = ++tot;
        cur = child[cur][pos];
        //cnt++[cur];
    }
    isWord[cur] = 1;
}
int query(string s) {
    int pos, cur = 0;
    memset(mp, 0, sizeof(mp));
    for (int i = 0; i < s.length(); ++i) {
        pos = s[i] - 'a';
        for(int j = 0; j < maxChild; ++j) {
            if(pos == j) continue;
            if(child[cur][j] != 0)
                mp[pos][j] = 1;
        }
        if (child[cur][pos] == 0)
            return 0;
        if(isWord[cur])
            return 0;
        cur = child[cur][pos];
    }
    return tuop() == 26;
}

string str[maxn];
int flag[maxn];
int main() {
#ifndef ONLINE_JUDGE
    FIN
#endif
    IO;
    int n;
    cin >> n;
    for(int i = 1; i <= n; i++) {
        cin >> str[i];
        insert(str[i]);
    }
    int ans = 0;
    for(int i = 1; i <= n; i++) {
        if(query(str[i])) {
            flag[i] = 1;
            ans++;
        }
    }
    // printf("%d\n", ans);
    cout << ans << '\n';
    for(int i = 1; i <= n; i++) {
        if(flag[i]) {
            cout << str[i] << '\n';
        }
    }


    return 0;
}

牛客wannafly 挑战赛14 B 前缀查询(trie树上dfs序+线段树)

链接:https://ac.nowcoder.com/acm/problem/15706

现在需要您来帮忙维护这个名册,支持下列 4 种操作:

  1. 插入新人名 si,声望为 a
  2. 给定名字前缀 pi 的所有人的声望值变化 di
  3. 查询名字为 sj 村民们的声望值的和(因为会有重名的)
  4. 查询名字前缀为 pj 的声望值的和

题解:一个非常明显的线段树操作,前缀可以看作是区间更新,区间查询,给定名字就是单点更新,单点查询,字典树上dfs序可以得到将树型结构变成一个线性的结构,然后用线段树维护即可,比较好的码力题了

/**
 *        ┏┓    ┏┓
 *        ┏┛┗━━━━━━━┛┗━━━┓
 *        ┃       ┃  
 *        ┃   ━    ┃
 *        ┃ >   < ┃
 *        ┃       ┃
 *        ┃... ⌒ ...  ┃
 *        ┃       ┃
 *        ┗━┓   ┏━┛
 *          ┃   ┃ Code is far away from bug with the animal protecting          
 *          ┃   ┃   神兽保佑,代码无bug
 *          ┃   ┃           
 *          ┃   ┃        
 *          ┃   ┃
 *          ┃   ┃           
 *          ┃   ┗━━━┓
 *          ┃       ┣┓
 *          ┃       ┏┛
 *          ┗┓┓┏━┳┓┏┛
 *           ┃┫┫ ┃┫┫
 *           ┗┻┛ ┗┻┛
 */
// warm heart, wagging tail,and a smile just for you!
//
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                           O\  =  /O
//                        ____/`---'\____
//                      .'  \|     |//  `.
//                     /  \|||  :  |||//  \
//                    /  _||||| -:- |||||-  \
//                    |   | \  -  /// |   |
//                    | \_|  ''\---/''  |   |
//                    \  .-\__  `-`  ___/-. /
//                  ___`. .'  /--.--\  `. . __
//               ."" '<  `.___\_<|>_/___.'  >'"".
//              | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//              \  \ `-.   \_ __\ /__ _/   .-` /  /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                     佛祖保佑      永无BUG
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef unsigned long long uLL;
#define ls rt<<1
#define rs rt<<1|1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define bug printf("*********\n")
#define FIN freopen("input.txt","r",stdin);
#define FON freopen("output.txt","w+",stdout);
#define IO ios::sync_with_stdio(false),cin.tie(0)
#define debug1(x) cout<<"["<<#x<<" "<<(x)<<"]\n"
#define debug2(x,y) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<"]\n"
#define debug3(x,y,z) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<" "<<#z<<" "<<z<<"]\n"
const int maxn = 3e5 + 5;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double Pi = acos(-1);
LL gcd(LL a, LL b) {
    return b ? gcd(b, a % b) : a;
}
LL lcm(LL a, LL b) {
    return a / gcd(a, b) * b;
}
double dpow(double a, LL b) {
    double ans = 1.0;
    while(b) {
        if(b % 2)ans = ans * a;
        a = a * a;
        b /= 2;
    } return ans;
}
LL quick_pow(LL x, LL y) {
    LL ans = 1;
    while(y) {
        if(y & 1) {
            ans = ans * x % mod;
        } x = x * x % mod;
        y >>= 1;
    } return ans;
}
struct Trie {
    int nxt[maxn][26], tot;
    int in[maxn], out[maxn], time_tag;
    void init() {
        memset(nxt, 0, sizeof(nxt));
        tot = 1;
        time_tag = 0;
    }
    void insert(string str) {
        int p = 1;
        int len = str.length();
        for(int i = 0; i < len; i++) {
            int ch = str[i] - 'a';
            if(!nxt[p][ch]) {
                nxt[p][ch] = ++tot;
            }
            p = nxt[p][ch];
        }
    }
    int query(string str) {
        int p = 1;
        int len = str.length();
        for(int i = 0; i < len; i++) {
            int ch = str[i] - 'a';
            if(!nxt[p][ch]) {
                return 0;
            }
            p = nxt[p][ch];
        }
        return p;
    }
    void dfs(int u) {
        in[u] = ++time_tag;
        for(int i = 0; i < 26; i++) {
            if(nxt[u][i]) {
                dfs(nxt[u][i]);
            }
        }
        out[u] = time_tag;
    }
} trie;
LL sum[maxn << 2];
int lazy[maxn << 2];
int cnt[maxn << 2];
void push_up(int rt) {
    sum[rt] = sum[ls] + sum[rs];
    cnt[rt] = cnt[ls] + cnt[rs];
}
void build(int l, int r, int rt) {
    sum[rt] = lazy[rt] = 0;
    if(l == r) return;
    int mid = (l + r) >> 1;
    build(lson);
    build(rson);
}
void push_down(int rt, int len) {
    if(lazy[rt]) {
        lazy[ls] += lazy[rt];
        lazy[rs] += lazy[rt];

        sum[ls] += lazy[rt] * cnt[ls];
        sum[rs] += lazy[rt] * cnt[rs];

        lazy[rt] = 0;
    }
}
void update_pos(int pos, int val, int l, int r, int rt) {
    if(l == r) {
        sum[rt] += val;
        cnt[rt]++;
        return;
    }
    int mid = (l + r) >> 1;
    push_down(rt, r - l + 1);
    if(pos <= mid) update_pos(pos, val, lson);
    else update_pos(pos, val, rson);
    push_up(rt);
}
void update(int L, int R, int val, int l, int r, int rt) {
    if(L <= l && r <= R) {
        sum[rt] += cnt[rt] * val;
        lazy[rt] += val;
        return;
    }
    int mid = (l + r) >> 1;
    push_down(rt, r - l + 1);
    if(L <= mid) update(L, R, val, lson);
    if(R > mid) update(L, R, val, rson);
    push_up(rt);
}
LL query(int L, int R, int l, int r, int rt) {
    if(L <= l && r <= R) {
        return sum[rt];
    }
    int mid = (l + r) >> 1;
    push_down(rt, r - l + 1);
    LL ans = 0;
    if(L <= mid) ans += query(L, R, lson);
    if(R > mid) ans += query(L, R, rson);
    return ans;
}
int op[maxn];
char buf[maxn];
string str[maxn];
int val[maxn];
int main() {
#ifndef ONLINE_JUDGE
    FIN
#endif
    int n;
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        scanf("%d %s", &op[i], buf);
        str[i] = buf;
        if(op[i] <= 2) {
            scanf("%d", &val[i]);
        }
    }
    trie.init();
    for(int i = 1; i <= n; i++) {
        if(op[i] == 1) {
            trie.insert(str[i]);
            // cout << str[i] << endl;
        }
    }
    trie.dfs(1);
    // bug;
    int tot = trie.tot;
    // debug1(tot);
    build(1, tot, 1);
    for(int i = 1; i <= n; i++) {
        if(op[i] == 1) {
            int u = trie.query(str[i]);
            int pos = trie.in[u];
            // debug1(pos);
            update_pos(pos, val[i], 1, tot, 1);
            // bug;
        } else if(op[i] == 2) {
            int u = trie.query(str[i]);
            if(u) {
                int l = trie.in[u];
                int r = trie.out[u];
                update(l, r, val[i], 1, tot, 1);
            }
        } else if(op[i] == 3) {
            int u = trie.query(str[i]);
            if(u) {
                int l = trie.in[u];
                int r = trie.in[u];
                LL ans = query(l, r, 1, tot, 1);
                printf("%lld\n", ans);
            } else {
                printf("0\n");
            }
        } else if(op[i] == 4) {
            int u = trie.query(str[i]);
            if(u) {
                int l = trie.in[u];
                int r = trie.out[u];
                LL ans = query(l, r, 1, tot, 1);
                printf("%lld\n", ans);
            } else {
                printf("0\n");
            }

        }
    }
    return 0;
}

牛客2018国庆集训 DAY1 D Love Live!(01字典树+启发式合并)

题意:给你一颗树,要求找出简单路径上最大权值为1~n每个边权对应的最大异或和

题解:

根据异或的性质我们可以得到 \(sum_{(u, v)}=sum_{(u, 1)} \bigoplus sum_{(v, 1)}\)那么我们可以预处理出所有简单路径上的异或值

对于路径上的最大权值来说,建图后,我们可以将边权进行排序,对于每一个权值为\(w_i(1-n)\)的连通块

现在我们已经得到了当前边权所在的连通块了,所以我们需要计算答案

也就是在这个边权所在的连通块内,计算出这个路径上所有边的异或和的最大值,我们可以用01字典树求出一个联通块内异或和的最大值

由于连通块的权值是从1开始的,所以对于权值为2的连通块来说,他是可以合并权值为1的块,我们用并查集将小的联通块往大的联通块上合并,这个就是启发式合并啦,基于一种贪心的思想

因为最多有n个联通块,合并的复杂度最多就是log(n)然后每次计算答案是log级别的,所以总的复杂度是nloglog级别的

/**
 *        ┏┓    ┏┓
 *        ┏┛┗━━━━━━━┛┗━━━┓
 *        ┃       ┃  
 *        ┃   ━    ┃
 *        ┃ >   < ┃
 *        ┃       ┃
 *        ┃... ⌒ ...  ┃
 *        ┃       ┃
 *        ┗━┓   ┏━┛
 *          ┃   ┃ Code is far away from bug with the animal protecting          
 *          ┃   ┃   神兽保佑,代码无bug
 *          ┃   ┃           
 *          ┃   ┃        
 *          ┃   ┃
 *          ┃   ┃           
 *          ┃   ┗━━━┓
 *          ┃       ┣┓
 *          ┃       ┏┛
 *          ┗┓┓┏━┳┓┏┛
 *           ┃┫┫ ┃┫┫
 *           ┗┻┛ ┗┻┛
 */
// warm heart, wagging tail,and a smile just for you!
//
//                            _ooOoo_
//                           o8888888o
//                           88" . "88
//                           (| -_- |)
//                           O\  =  /O
//                        ____/`---'\____
//                      .'  \|     |//  `.
//                     /  \|||  :  |||//  \
//                    /  _||||| -:- |||||-  \
//                    |   | \  -  /// |   |
//                    | \_|  ''\---/''  |   |
//                    \  .-\__  `-`  ___/-. /
//                  ___`. .'  /--.--\  `. . __
//               ."" '<  `.___\_<|>_/___.'  >'"".
//              | | :  `- \`.;`\ _ /`;.`/ - ` : | |
//              \  \ `-.   \_ __\ /__ _/   .-` /  /
//         ======`-.____`-.___\_____/___.-`____.-'======
//                            `=---='
//        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                     佛祖保佑      永无BUG
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <bitset>
#include <cstdio>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
typedef unsigned long long uLL;
#define ls rt<<1
#define rs rt<<1|1
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define bug printf("*********\n")
#define FIN freopen("input.txt","r",stdin);
#define FON freopen("output.txt","w+",stdout);
#define IO ios::sync_with_stdio(false),cin.tie(0)
#define debug1(x) cout<<"["<<#x<<" "<<(x)<<"]\n"
#define debug2(x,y) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<"]\n"
#define debug3(x,y,z) cout<<"["<<#x<<" "<<(x)<<" "<<#y<<" "<<(y)<<" "<<#z<<" "<<z<<"]\n"
const int maxn = 1e5 + 5;
const int INF = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const double Pi = acos(-1);
LL gcd(LL a, LL b) {
    return b ? gcd(b, a % b) : a;
}
LL lcm(LL a, LL b) {
    return a / gcd(a, b) * b;
}
double dpow(double a, LL b) {
    double ans = 1.0;
    while(b) {
        if(b % 2)ans = ans * a;
        a = a * a;
        b /= 2;
    } return ans;
}
LL quick_pow(LL x, LL y) {
    LL ans = 1;
    while(y) {
        if(y & 1) {
            ans = ans * x % mod;
        } x = x * x % mod;
        y >>= 1;
    } return ans;
}
struct EDGE {
    int u, v, w, nxt;
    EDGE() {};
    EDGE(int _u, int _v, int _w) {
        u = _u;
        v = _v;
        w = _w;
    }
} edge[maxn << 1], G[maxn];
int head[maxn], tot;
bool cmp(EDGE a, EDGE b) {
    return a.w < b.w;
}
void add_edge(int u, int v, int w) {
    edge[tot].v = v;
    edge[tot].w = w;
    edge[tot].nxt = head[u];
    head[u] = tot++;
}
int pre[maxn];
void dfs(int u, int fa) {
    for(int i = head[u]; i != -1; i = edge[i].nxt) {
        int v = edge[i].v;
        if(v == fa) continue;
        pre[v] = pre[u] ^ edge[i].w;
        dfs(v, u);
    }
}
struct Trie {
    int id[maxn];
    int ch[maxn * 400][2];
    int cnt;
    void init() {
        memset(ch, 0, sizeof(ch));
        cnt = 0;
    }
    void insert(int rt, int x) {
        bitset<20> bit;
        bit = x;
        for(int i = 19; i >= 0; i--) {
            if (!ch[rt][bit[i]])
                ch[rt][bit[i]] = ++cnt;
            rt = ch[rt][bit[i]];
        }
    }
    int query(int rt, int x) {
        bitset<20> bit;
        bit = x;
        int res = 0;
        for(int i = 19; i >= 0; i--) {
            bool flag = true;
            int id = bit[i] ^ 1;
            if(!ch[rt][id]) {
                flag = false;
                id ^= 1;
            }
            if(flag) res += 1 << i;
            rt = ch[rt][id];
        }
        return res;
    }
} trie;
int fa[maxn];
int find(int x) {
    return x == fa[x] ? x : fa[x] = find(fa[x]);
}
void merge(int x, int y) {
    x = find(x);
    y = find(y);
    if(x != y) {
        fa[y] = x;
    }
}
int n;
int sz[maxn];
vector<int> vec[maxn];
void init() {
    memset(head, -1, sizeof(head));
    tot = 0;
    trie.init();
    trie.cnt = n + 1;
    pre[1] = 0;
    for(int i = 1; i <= n; i++) {
        fa[i] = i;
        sz[i] = 1;
        vec[i].clear();
        trie.id[i] = i;
    }
}
int main() {
#ifndef ONLINE_JUDGE
    FIN
#endif

    scanf("%d", &n);
    init();
    for(int i = 1; i < n; i++) {
        int u, v, w;
        scanf("%d%d%d", &u, &v, &w);
        add_edge(u, v, w);
        add_edge(v, u, w);
        G[i] = EDGE(u, v, w);
    }
    dfs(1, 1);
    // for(int i = 1; i <= n; i++) {
    //     printf("%d ", pre[i]);
    // }
    // printf("\n");
    for (int i = 1; i <= n; ++i) {
        trie.insert(trie.id[i], pre[i]);
        vec[i].push_back(pre[i]);
    }
    // for(int i=1;i<=n;i++){
    //     printf("%d\n",fa[i]);
    // }
    sort(G + 1, G + n, cmp);
    for (int i = 1; i < n; ++i) {
        int x = G[i].u, y = G[i].v;
        int fx = find(x), fy = find(y);

        if (sz[fx] > sz[fy]) {
            swap(x, y);
            swap(fx, fy);
        }
        int res = 0;
        for (auto it : vec[fx]) {
            res = max(res, trie.query(trie.id[fy], it));
        }
        for (auto it : vec[fx]) {
            trie.insert(trie.id[fy], it);
            vec[fy].push_back(it);
        }
        fa[fx] = fy;
        sz[fy] += sz[fx];
        printf("%d%c", res, i == n - 1 ? '\n' : ' ');
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/buerdepepeqi/p/11645361.html
今日推荐