POJ2513 Colored Sticks

36 篇文章 0 订阅

这题综合性蛮强,数据结构使用到了并查集+trie树,理论用到了欧拉回路。

颜色为图中的节点,棍子为边。并查集的元素是数字,要把颜色string隐射到数字,

用STL的map进行索引竟然超时。 那于是就用trie树吧。

#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <list>
#include <set>
#include <time.h>
#include <string.h>
#include <string>
#include <iostream>
#include <map>
using namespace std;

int id = 0;
int father[500010];
int Rank[500010];
int delta[500010];
char word1[20];
char word2[20];

struct TreeNode{
	int exist;
	int index;
	TreeNode *next[26];
	TreeNode():exist(0),index(-1){
		memset(next,0,sizeof(next));
	}
};

TreeNode *root = new TreeNode();

void insert(char *word){
	TreeNode *loc = root;
	while(*word != '\0'){
		if(!loc->next[*word - 'a'])
			loc->next[*word-'a'] = new TreeNode();
		loc = loc->next[*word - 'a'];
		++word;
	}
	if(loc->exist==0){
		loc->exist = 1;
		loc->index = id++;
	}
}

int get_index(char *word){
	TreeNode *loc = root;
	while(*word != '\0'){
		loc = loc->next[*word-'a'];
		++word;
	}
	return loc->index;
}


void make_set(int x){
	father[x] = x;
	Rank[x] = 0;
}
int find_set(int x){
	if(father[x]!=x){
		father[x] = find_set(father[x]);
	}
	return father[x];
}
void union_set(int i, int j){
	int x = find_set(i);
	int y = find_set(j);
	if(x==y)
		return;
	if(Rank[x]>Rank[y])
		father[y] = x;
	else{
		father[x] = y;
		if(Rank[x]==Rank[y])
			++Rank[y];
	}
}

void process(){
	int count = 0;
	for(int i=0;i<id;++i)
		if(delta[i]%2==1)
			++count;
	if(count!=0 && count!=2){
		printf("Impossible\n");
		return;
	}
	for(int i=1;i<id;++i)
		if(find_set(i)!=find_set(i-1)){
			printf("Impossible\n");
			return;
		}
	printf("Possible\n");
}

int main(){
	for(int i=0;i<500000;++i)
		make_set(i);
	int x,y;		
	while(scanf("%s %s",word1,word2)!=EOF){
		insert(word1);
		insert(word2);
		x = get_index(word1);
		y = get_index(word2);
		++delta[x];
		++delta[y];
		union_set(x,y);
	}
	process();
	//system("pause");
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值