pku 2513 Colored Sticks trie树+并查集+欧拉路的判断

http://poj.org/problem?id=2513

才开始自己对欧拉路的理解成了汉密尔顿路;

欧拉路:给定无孤立节点的图G,(连通图),若存在一条路,经过图中每边一次且仅一次,该条路是欧拉路;

汉密尔顿路则是:给定无孤立节点的图G,(连通图),若存在一条路,经过图中每点一次且仅一次,该条路是汉密尔顿路;

这样用字典树映射字符串的编号,并查集判断连通,

欧拉路判断:

1 :必须是连通图;

2:有0个或2个奇数度数的节点

View Code
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#define maxn 500007
using namespace std;

struct node
{
int flag;
node *next[26];
}*head, H[maxn];
int pos;
int de[maxn],L,f[maxn];

void init()
{
int i;
for (i = 0; i < maxn; ++i)
{
f[i] = i;
de[i] = 0;
}
pos = L = 0;
head = &H[pos++];
}

node* newnode()
{
int i = 0;
node *p = &H[pos++];
for (i = 0; i < 26; ++i)
p->next[i] = NULL;
p->flag = 0;
return p;
}

int insert(char *s)
{
int i,k;
int len = strlen(s);
node *q;
q = head;
for (i = 0; i < len; ++i)
{
k = s[i] - 'a';
if (q->next[k] == NULL)
q->next[k] = newnode();
q = q->next[k];
}
if (!q->flag)
q->flag = ++L;
return q->flag;
}
int find(int x)
{
if (x != f[x])
f[x] = find(f[x]);
return f[x];
}
void Union(int x,int y)
{
x = find(x);
y = find(y);
if (x != y)
f[y] = x;
}
int main()
{
char s1[13],s2[13];
int x,y,i;
init();
while (~scanf("%s%s",s1,s2))
{
x = insert(s1);
de[x]++;
y = insert(s2);
de[y]++;
Union(x,y);
}
int tmp = find(1);
int ct = 0;
bool flag = false;
for (i = 1; i <= L; ++i)
{
//printf("%d\n",de[i]);
if (tmp != find(i))
{
flag = true;
break;
}
if (de[i]&1) ct++;
}
if (flag)
{
printf("Impossible\n");
}
else//首先是连通
{
if (ct == 2 || ct == 0)//0或2个奇数度数节点
printf("Possible\n");
else
printf("Impossible\n");
}
return 0;
}



posted @ 2012-04-02 22:12  E_star  阅读(229)  评论(0编辑  收藏  举报