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

版权声明:From: http://blog.csdn.net/tju_tahara https://blog.csdn.net/TJU_Tahara/article/details/77370535

Colored Sticks
Time Limit: 5000MS   Memory Limit: 128000K
Total 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 red
red violet
cyan blue
blue magenta
magenta cyan

Sample Output

Possible

Hint

Huge input,scanf is recommended.

Source



题目大意:

扫描二维码关注公众号,回复: 3852236 查看本文章

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


分析:

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

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

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



#include <iostream>
#include <map>
#include <queue>
#include <algorithm>
#include <cstdio>
#include <cstring>
#define MAX 600500

using 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;
}



猜你喜欢

转载自blog.csdn.net/TJU_Tahara/article/details/77370535
今日推荐