poj 字符串相关之2513 Colored Sticks
方法:Trie树+并查集+欧拉回路相关知识(度为0/2)
Accepted 73336K 1344MS
#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
//#include<math.h>
#include<algorithm>
#include<vector>
#include<map>
#define MAXNUM 500020
#define LL long long
using namespace std;
int n, degree[MAXNUM], Pre[MAXNUM];
class node
{
public:
int idx;
node* next[26];
node()
{
idx = -1;
for (int i = 0; i < 26; i++)
next[i] = NULL;
}
};
class Trie
{
public:
node* root;
Trie()
{
root = new node();
}
int Find(char * s)
{
int i, len, tmp;
node * cur;
cur = root;
len = strlen(s);
for (i = 0; i < len; i++)
{
tmp = s[i] - 'a';
if (cur->next[tmp] == NULL)
cur->next[tmp] = new node();
cur = cur->next[tmp];
}
if (cur->idx == -1)
{
cur->idx = n++;
}
return cur->idx;
}
};
int find(int x)
{
while (Pre[x] != x) x = Pre[x];
return x;
}
void Union(int i, int j)
{
int a, b;
a = find(i);
b = find(j);
if (a != b)
Pre[b] = a;
}
int main(void)
{
//freopen("1.txt", "r", stdin);
int i, j, k, count;
char str1[20], str2[20];
Trie tree;
n = 1;
memset(degree, 0, sizeof(degree));
for (k = 1; k < MAXNUM; k++)
Pre[k] = k;
while (scanf("%s%s", str1, str2) != EOF)
{
i = tree.Find(str1);
j = tree.Find(str2);
degree[i]++;
degree[j]++;
Union(i, j);
}
//检查度
count = 0;
for (i = 1; i < n; i++)
{
if (degree[i] % 2 == 1)
count++;
}
if (count != 2 && count != 0)
{
printf("Impossible\n");
return 0;
}
//检查连通性
k = find(1);
for (i = 2; i < n; i++)
{
if (find(i) != k)
{
printf("Impossible\n");
return 0;
}
}
printf("Possible\n");
}