POJ-2513-Colored Sticks

来源:互联网 发布:手机屏保软件下载 编辑:程序博客网 时间:2024/06/03 09:38
Colored Sticks
Time Limit: 5000MS Memory Limit: 128000KTotal Submissions: 35039 Accepted: 9155

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 redred violetcyan blueblue magentamagenta cyan

Sample Output

Possible

Hint

Huge input,scanf is recommended.

n根木棒,木棒两端都有颜色,判断能不能把木棒合并成一条,接触的木棒端必须是相同颜色的。
给定一些木棒,木棒两端都涂上颜色,求是否能将木棒首尾相接,连成一条直线,要求不同木棒相接的一边必须是相同颜色的。

欧拉回路判断能否连通
并查集判断是否连成一条
字典树存储颜色

#include<iostream>#include<string.h>#include<stdio.h>#include<math.h>#include<algorithm>#include<queue>#include<vector>using namespace std;const int MAX = 500010;int pre[MAX], cnt = 0, color[MAX];struct node{    int data;    struct node *next[26];}*root;int Search(char *s){    node *p = root;    for(int i = 0; s[i]; ++i)    {        int t = s[i]-'a';        if(p->next[t]!=NULL)p = p->next[t];        else return 0;    }    return p->data;}struct node *creat(){    node *p = new node;    for(int i = 0;i<26;++i)        p->next[i] = NULL;    return p;};void add(char *s, int x){    node *p = root;    for(int i = 0; s[i];++i)    {        int t = s[i]-'a';        if(p->next[t]==NULL)            p->next[t] = creat();        p = p->next[t];    }    p->data =x;}int Find(int x){    if(x != pre[x])    {        pre[x] = Find(pre[x]);    }    return pre[x];}bool Judge(){    int p = 0;    for(int i = 1;i<=cnt;++i)    {        if(color[i]%2==1)++p;    }    if(p!=2&&p!=0)return false;    p = Find(1);    for(int i =2; i<=cnt;++i)    {        if(p!=Find(i))return false;    }    return true;}int main(){    for(int i = 0; i<MAX; ++i)        pre[i] = i;    memset(color, 0, sizeof(color));    char str1[15], str2[15];    root = creat();    while(scanf("%s %s", str1, str2) != EOF)    {        int a = Search(str1), b = Search(str2);        if(a==0)            add(str1, a = ++cnt);        if(b==0)            add(str2, b = ++cnt);        color[a]++;        color[b]++;        int aa = Find(a), bb = Find(b);        if(aa!=bb)pre[aa] = bb;    }    if(Judge())printf("Possible\n");    else printf("Impossible\n");    return 0;}



0 0