POJ2513(Colored Sticks)

Colored Sticks

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

思路

题意很多棍子,颜色相同的两端可以拼接在一起,问所有的棍子能不能拼成一根长棍子。emmm…欧拉路问题,只不过要对这个单词做一个hash吧。然后hash的方式比较多,反正比较容易想到的就是map,unorder_map(哈希表),字典树。北大OJ真的是太老了,map超时可能是我手法问题?unorder_map不支持会报编译错误…只能硬着头皮写字典树手动hash了。

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <map>
#include <algorithm>
using namespace std;
const int maxn = 500005;
int trie[maxn][26];
int num[maxn];
int s[maxn];
int in[maxn];
int cnt,res;
int height[maxn];			//按高度合并降一点复杂度,也可以不写。
void clear_set()
{
	res = cnt = 0;
	memset(height,0,sizeof(height));
	memset(in,0,sizeof(in));
	for(int i = 0;i < maxn;i++){
		s[i] = i;
	}
}
int insert_s(char *s)
{
	int n = strlen(s);
	int root = 0;
	for(int i = 0;i < n;i++){
		int k = s[i] - 'a';
		if(!trie[root][k]){
			trie[root][k] = ++cnt;
		}
		root = trie[root][k];
	}
	if(!num[root]){
		num[root] = ++res;
	}
	return num[root];
}
int find_set(int x)
{
	if(s[x] != x){
		s[x] = find_set(s[x]);
	}
	return s[x];
}
void union_set(int x,int y)
{
	int fx = find_set(x);
	int fy = find_set(y);
	if(fx == fy)	return ;
	if(height[fx] == height[fy]){
		s[fy] = fx;
		height[fx]++;
	}
	else{
		if(height[fx] < height[fy]){
			s[fx] = fy;
		}
		else{
			s[fy] = fx;
		}
	}
}
int main()
{
	char t[30],p[30];
	clear_set();
	while(scanf("%s%s",t,p)!= EOF){
		int x = insert_s(t);
		int y = insert_s(p);
		in[x]++;in[y]++;
		union_set(x,y);	
	}
	int sum = 0,ans = 0;
	for(int i = 1;i <= res;i++){
		if(s[i] == i){
			ans++;
		}
		if(in[i]%2){
			sum++;
		}
	}
	if(ans > 1){
		printf("Impossible\n");
	}
	else{
		if(sum ==2 || sum == 0){
			printf("Possible\n");
		}
		else{
			printf("Impossible\n");
		}
	}
	return 0;
}

愿你走出半生,归来仍是少年~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章