POJ 2513 Colored Sticks 【Trie树】

Trie树+欧拉路径的判定。

并查集来判断连通性,然后判断欧拉路径的条件就可以了。



Trie树的插入操作和查询Index操作,其他操作没有写。

没有写全的模板。


#include <cstdio>
#include <cstring>
using namespace std;
#define N 500002
struct node {
    int num;
    bool is_word;
    node *next[26];
    node() {
        num = 0;
        is_word = false;
        memset(next, NULL, sizeof(next));
    }
} root;
int n, c[N] = {0}, f[N] = {0};

void Insert(char s[]) {
    node *p = &root;
    for (int i=0; s[i]; i++) {
        int x = s[i] - 'a';
        if (p->next[x] == NULL)
            p->next[x] = new node;
        p = p->next[x];
    }
    if (!p->is_word) {
        p->is_word = true;
        p->num = ++n;
    }
}
int Index(char s[]) {
    node *p = &root;
    for (int i=0; s[i]; p=p->next[s[i]-'a'], i++) ;
    return p->num;
}
int find_set(int x) {
    if (x == f[x]) return x;
    return f[x] = find_set(f[x]);
}
int main() {
    char a[11], b[11];
    n = 0;
    int ia, ib;
    while (scanf(" %s %s", a, b) == 2) {
        Insert(a); Insert(b);
        ia = Index(a); ib = Index(b);
        c[ia]++, c[ib]++;
        if (f[ia] == 0) f[ia] = ia;
        if (f[ib] == 0) f[ib] = ib;
        f[find_set(ia)] = f[find_set(ib)];
    }
    int cnt = 0;
    bool flag = true;
    for (int i=1; i<=n; i++) {
        if (c[i] & 1) cnt++;
        if (find_set(i) != f[1])
            flag = false;
    }
    if ((cnt==0 || cnt==2) && flag) printf("Possible\n");
    else printf("Impossible\n");


    return 0;
}


原文地址:https://www.cnblogs.com/javawebsoa/p/3097633.html