-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlayOnWords.java
92 lines (90 loc) · 1.93 KB
/
PlayOnWords.java
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package ques;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PlayOnWords {
public static int[] in;
public static int[] out;
public static int[][] edge;
public static int[] visited;
public static int[] v;
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t>0){
t--;
int n=Integer.parseInt(br.readLine());
in=new int[26];
out=new int[26];
edge=new int[26][26];
visited=new int[26];
v=new int[26];
while(n>0){
n--;
String s=br.readLine();
out[s.charAt(0)-'a']++;
in[s.charAt(s.length()-1)-'a']++;
edge[s.charAt(0)-'a'][s.charAt(s.length()-1)-'a']=1;
edge[s.charAt(s.length()-1)-'a'][s.charAt(0)-'a']=1;
v[s.charAt(0)-'a']=1;
v[s.charAt(s.length()-1)-'a']=1;
}
int i=0;
while(v[i]==0){
i++;
}
visit(i);
int flag1=0;
for(i=0;i<26;i++){
if(v[i]==1 && visited[i]==0){
flag1=1;
break;
}
}
int v1=-1,v2=-1,exist=-1;
if(flag1==0){
for(i=0;i<26;i++){
if(in[i]!=out[i]){
if(v1==-1){
v1=i;
}
else if(v2==-1){
v2=i;
}
else{
exist=0;
break;
}
}
}
}
if(flag1==1 || exist==0){
System.out.println("The door cannot be opened.");
continue;
}
else{
if(v1==-1){
System.out.println("Ordering is possible.");
exist=1;
}
else if(in[v1]==out[v1]+1 && in[v2]+1==out[v2]){
System.out.println("Ordering is possible.");
exist=1;
}
else if(in[v2]==out[v2]+1 && in[v1]+1==out[v1]){
System.out.println("Ordering is possible.");
exist=1;
}
else
System.out.println("The door cannot be opened.");
}
}
}
public static void visit(int x){
visited[x]=1;
for(int i=0;i<26;i++){
if((edge[x][i]==1||edge[i][x]==1)&& visited[i]==0){
visit(i);
}
}
}
}