您的位置:首页 > 其它

poj Colored Sticks(2513)

2014-08-12 15:39 260 查看
Colored Sticks

Time Limit: 5000MSMemory Limit: 128000K
Total Submissions: 30201Accepted: 7975
Description

You are given a bunch of wooden sticks. Each endpoint of each stick is colored with some color. Is it possible to align the sticks in a straight line such that the colors of the endpoints that touch are of the same color?
Input

Input is a sequence of lines, each line contains two words, separated by spaces, giving the colors of the endpoints of one stick. A word is a sequence of lowercase letters no longer than 10 characters. There is no more than 250000 sticks.
Output

If the sticks can be aligned in the desired way, output a single line saying Possible, otherwise output Impossible.
Sample Input
blue red
red violet
cyan blue
blue magenta
magenta cyan

Sample Output
Possible

Hint

Huge input,scanf is recommended.
题目大意:
给你一些两端带有不同颜色的木棍,问你是否可以经过重组,使得这些棍子排成一条直线且任一相邻颜色相同。

题目分折:

判定无向图的 欧拉通路 。(图连通,图中只有 0个或者2个度为奇数的顶点)。给每一种颜色用字典树定义为一个结点(很容易),与些同时使用并查集(图连通)。

题目链接:http://poj.org/problem?id=2513

小乐一下:

图有两种,有向的,无向的,路有一两种,欧拉通路,欧拉回路。

无向图:

欧拉通路:图连通,图中只有0个或者2个度为奇数的节点。

欧拉回路:图连通,所有结点的度均为偶数。

有向图:

欧拉通路:图连通,除两个端点外其余结点的入度等于出度,其中一个结点的入度比出度大一,号一个结点的入度比出度小一。 或者所有入度等于出度。

欧拉回路:图连通,所有结点的入度等于出度。

代码:

#include<cstdio>
#include<cstring>
#include<malloc.h>
#include<cstdlib>
const int maxn = 500010;
typedef struct TrieNode{
int x;
struct TrieNode * next[26];
}*Trie;
Trie Root;
int d[maxn],father[maxn];
int cnt;
void Init(){
for(int i = 1;i<maxn;i++) father[i] = i;
memset(d,0,sizeof(d));
cnt = 0;
}
Trie CreateTrie(){
Trie p = (Trie) malloc (sizeof(struct TrieNode));
for(int i = 0;i<26;i++) p->next[i] = NULL;
p->x = 0;
return p;
}
void InsertTrie(Trie &pRoot,char *s,int x){
Trie p = pRoot;
int i = 0,k;
while(s[i]){
k = s[i++]-'a';
if(p->next[k] == NULL) p->next[k] = CreateTrie();
p = p->next[k];
}
p->x = x;   //给这种颜色设定一个结点编号。
}
int SearchTrie(Trie &pRoot,char *s){
Trie p = pRoot;
int i = 0,k;
while(s[i]){
k = s[i++]-'a';
if(p->next[k] == NULL) return 0;
p = p->next[k];
}
return p->x;  //返回这个颜色所对应的编号。
}
int Find(int x){
return x==father[x]?x:father[x] = Find(father[x]);
}
bool judge(){     //无向图的欧拉通路的判定方法。
int odd = 0;
for(int i = 1;i<=cnt;i++){
if(d[i]%2) odd ++;
}
if(odd != 0 && odd != 2) return false;
int x = Find(1);
for(int i = 2;i<=cnt;i++){
if(Find(i)!=x) return false;
}
return true;
}
int main(){
char s1[12],s2[12];
int x,y,fx,fy;
Root = CreateTrie();
Init();
while(scanf("%s%s",s1,s2)!=EOF){
x = SearchTrie(Root,s1);y = SearchTrie(Root,s2);
if(x==0) InsertTrie(Root,s1,x=++cnt);
if(y==0) InsertTrie(Root,s2,y=++cnt);
d[x]++;d[y]++;      //统计对应结点的度
fx = Find(x);fy = Find(y);   // 同时使用并查集,方便判定 图是否 连通。
if(fx != fy) father[fx] = fy;
}
if(judge()) printf("Possible\n");
else printf("Impossible\n");
return 0;
}


伟大的梦想成就伟大的人,从细节做好,从点点滴滴做好,从认真做好。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: