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

願你走出半生,歸來仍是少年~

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