poj 2513 trie树

题目大意:

输入木棒两端的颜色,一端颜色相同的木棒才能连接,问最后能不能连接成一根木棒

思路:

欧拉回路:如果图G中的一个路径包括每个边恰好一次,则该路径称为欧拉路径,如果一个回路是欧拉路径,则称为欧拉回路

无向图存在欧拉回路的充要条件 一个无向图存在欧拉回路,当且仅当该图所有顶点度数都为偶数,且该图是连通图。
有向图存在欧拉回路的充要条件 一个有向图存在欧拉回路,所有顶点的入度等于出度且该图是连通图。

本题用并查集判断是不是连通图,用TRIE树对应颜色相应的编号(map超时)

Sample Input

blue red
red violet
cyan blue
blue magenta
magenta cyan

Sample Output

Possible
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <string.h>
#include <queue>
using namespace std;
const int MAXN = 500010;
struct tree {
    int id;
    tree* next[30];
    tree() {
        id = 0;
        memset(next, NULL, sizeof(next));
    }
};
int father[MAXN];
int d[MAXN] = { 0 };
tree* root = new tree;
int color = 0;
int find(int x) {
    if (father[x] == x)return x;
    return father[x] = find(father[x]);
}
void merge(int a, int b) {
    father[find(a)] = find(b);
}
int insert(char s[]) {
    tree* p = root;
    int l = strlen(s);
    for (int i = 0; i < l; i++) {
        if (p->next[s[i] - 'a'] == NULL) {
            p->next[s[i] - 'a'] = new tree;
        }
        p = p->next[s[i] - 'a'];
    }
    if (p->id != 0)return p->id;
    else {
        p->id = ++color;
        return p->id;
    }
}
int main() {
    char a[30], b[30];
    for (int i = 0; i < MAXN; i++)father[i] = i;
    while (scanf("%s %s",a,b)!=EOF) {
        int x = insert(a);
        int y = insert(b);
        merge(x, y);
        d[x]++;
        d[y]++;
    }
    int num1 = 0, num2 = 0;
    for (int i = 1; i <= color; i++) {
        if (father[i] == i)num1++;
        if (d[i] % 2 != 0)num2++;
    }
    //cout << num1 << " " << num2 << endl;
    if (num1 > 1 || (num2 != 2&&num2!=0))cout << "Impossible" << endl;
    else cout << "Possible" << endl;

}

    原文作者:Trie树
    原文地址: https://blog.csdn.net/y201619819/article/details/81022513
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞