POJ 2513 Colored Sticks(字典树+欧拉回路)

来源:互联网 发布:王坚 阿里云 编辑:程序博客网 时间:2024/06/06 07:39

Colored Sticks
Time Limit: 5000MS Memory Limit: 128000KTotal Submissions: 37665 Accepted: 9873

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.

Source

The UofA Local 2000.10.14


题目大意:

给你好多木棍,两端涂上颜色,如果两端颜色相同就可以接在一起。问是否可以接成一个长木棍。


分析:

其实是字典树+欧拉回路判断的水题。自己纠结了半天的骚搞……最后WA了很多发。

大概就是字典树建树然后用字典树hash建图, 如果有颜色ab的木棍, 就把a和b连上边,最后判断图是否可以一笔画遍历所有的边即可。记得判断空集,空集需要输出可以。

(据说数据范围有问题,因为WA的次数太多也不知道是不是有问题了)



#include <iostream>#include <map>#include <queue>#include <algorithm>#include <cstdio>#include <cstring>#define MAX 600500using std::queue;struct node{int num, nxt[26];}tire[MAX * 27]; int top, htop;int nxt[MAX];bool  flg[MAX];int get(char str[]){int len = strlen(str), i, now = 0;for(i = 0; i < len; i++){if(tire[now].nxt[str[i] - 'a'] == 0){tire[now].nxt[str[i] - 'a'] = top++;}now = tire[now].nxt[str[i] - 'a'];}if(tire[now].num == 0) tire[now].num = htop++;return tire[now].num;}struct node2{int t, nxt;}edge[MAX * 2]; int head[MAX], inde, deg[MAX], oc[MAX];void fresh(){memset(head, -1, sizeof(head));inde = 0;}void addedge(int s,int t){edge[inde].t = t;edge[inde].nxt = head[s];head[s] = inde++;deg[s]++;}bool judge(){queue<int> que;int i, now, cnt;que.push(1);oc[1] = 1;cnt = 1;while(!que.empty()){now = que.front();que.pop();i = head[now];while(i >= 0){if(!oc[edge[i].t]){oc[edge[i].t] = 1;que.push(edge[i].t);cnt++;}i = edge[i].nxt;}}if(cnt != htop - 1) return false;cnt = 0;for(i = 1; i < htop; i++){if(deg[i] & 1) cnt++;}if(cnt > 2) return false;return true;}int main(){top = htop = 1;char s1[11], s2[11];int h1, h2, i, cnt;fresh();while(~scanf("%s%s", s1, s2)){h1 = get(s1);h2 = get(s2);addedge(h1, h2);addedge(h2, h1);}if(judge() || htop == 1)printf("Possible\n");else printf("Impossible\n");return 0;}



阅读全文
0 0
原创粉丝点击