Colored Sticks
time limit per test 2 second memory limit per test 256 megabytes
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?

传送门:POJ2513

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

1
2
3
4
5
blue red
red violet
cyan blue
blue magenta
magenta cyan

Sample Output

1
Possible

题解

好题 真的好题 第一步需要建模 本题每个颜色相当于一点 那么每根棍子就是连接两点的一条边 题目要求就是能不能经过所有边将图一笔画 这就变成判断欧拉通路了 欧拉通路判定条件 1:全部连通 此处用并查集判断 2:奇度点不超过2个 此处用数组记录下就好 最后可用trie或者hashmap为每一个字符串编号
## AC code:(不包含输入类)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.io.*;  
import java.util.*;
public class Main {
static int[]pre=new int[500050];
static int[]js=new int[500050];
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter(System.out);
HashMap<String,Integer>map=new HashMap<String,Integer>();
int count=0;
for(int i=0;i<500050;i++)pre[i]=i;
while(sc.hasNext()){
String s1=sc.next();
String s2=sc.next();
if(!map.containsKey(s1)){
map.put(s1, count++);
}
if(!map.containsKey(s2)){
map.put(s2, count++);
}
int a=map.get(s1);
int b=map.get(s2);
union(a,b);
js[a]++;
js[b]++;
}
boolean flag=true;
int c=0;
int d=0;
for(int i=0;i<count;i++){
if(find(i)==i){
c++;
}
if(js[i]%2!=0)d++;
}
if(c>=2)flag=false;
if(d>2)flag=false;
if(flag)pw.println("Possible");
else pw.println("Impossible");
pw.flush();
}
static int find(int x){
if(x==pre[x])return x;
int root=find(pre[x]);
return pre[x]=root;
}
static void union(int a,int b){
int fa=find(a);
int fb=find(b);
if(fa!=fb){
pre[fa]=fb;
}
}
}