题目大意:http://poj.org/problem?id=2513
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.
If the sticks can be aligned in the desired way, output a single line saying Possible, otherwise output Impossible.
blue red
red violet
cyan blue
blue magenta
magenta cyan
Possible
解题思路:可以考虑把每个颜色建成一个节点,题目要求把所有的木棍拼成一条直线,所以也就是说除了两端的端点,中间的节点的度数都是偶数,所以题目也就变成了能否构成这么一条欧拉通路,因为题目数据比较大,所以不能使用map,只能使用字典树,统计每个节点的度数。不过最后需要判断一下是否是连通图,所以需要用并查集,判断一下。
AC代码:
/*
@Author: wchhlbt
@Date: 2017/4/18
*/
//#include <bits/stdc++.h>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <limits>
#include <climits>
#include <cstdio>
#define Fori(x) for(int i=0;i<x;i++)
#define Forj(x) for(int j=0;j<x;j++)
#define maxn 520000
#define inf 0x3f3f3f3f
#define ONES(x) __builtin_popcount(x)
using namespace std;
typedef long long ll ;
const double eps =1e-8;
const int mod = 1000000007;
typedef pair<int, int> P;
const double PI = acos(-1.0);
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
int color,cnt;
int deg[maxn];
//数组式写法的字典树
struct Node
{
int num;//记录每个单词出现的次数
int pNext[26];
}node[maxn<<4];
int Insert(char s[])
{
int p = 0;
int len = strlen(s);
for(int i = 0; i<len; i++){
int m = s[i] - 'a';
if (!node[p].pNext[m]) {
node[p].pNext[m] = ++cnt;
for(int j = 0; j<26; j++)
node[cnt].pNext[j] = 0;
node[cnt].num = 0;
}
p = node[p].pNext[m];
}
if(node[p].num==0)
node[p].num = color++;
return node[p].num;
}
//并查集
int city[maxn];
int getcity(int point)
{
if(city[point] == point)
{
return point;
}
else
{
city[point] = getcity(city[point]);
return city[point];
}
}
bool connect(int point1,int point2)
{
int t1,t2;
t1 = getcity(point1);
t2 = getcity(point2);
if(t1!=t2)
{
city[t2] = t1;
return true;
}
return false;
}
void init()
{
for(int i = 1; i<=maxn-2; i++)
{
city[i] = i;
}
}
int main()
{
color = 1;
init();
char str[20];
while(~scanf("%s",str))
{
int id1 = Insert(str);
scanf("%s",str);
int id2 = Insert(str);
deg[id1]++; deg[id2]++;
connect(id1,id2);
}
int k = 0;
for(int i = 1; i<color; i++)
{
if(deg[i]%2)
k++;
}
if(k!=0 && k!=2){
printf("Impossible\n");
}
else{
int ans = getcity(1);
for(int i = 1; i<color; i++){
if(getcity(i)!=ans){
printf("Impossible\n");
return 0;
}
}
printf("Possible\n");
}
return 0;
}