1
+ import java .math .BigInteger ;
2
+ import java .util .*;
3
+
4
+ public class Main {
5
+ static int ansi = 0 ;
6
+
7
+ public static void main (String [] args ) {
8
+ Scanner scanner = new Scanner (System .in );
9
+ int n = scanner .nextInt ();
10
+ ArrayList <Integer > arrayList [] = new ArrayList [n ];
11
+ int arr [] = new int [n ];
12
+ HashMap <String , Integer > hashMap = new HashMap <>();
13
+ for (int i = 0 ; i < n ; i ++) {
14
+ arrayList [i ] = new ArrayList <>();
15
+ }
16
+ ArrayList <String > names = new ArrayList <>();
17
+ for (int i = 0 ; i < n ; i ++) {
18
+ String name = scanner .next ();
19
+ hashMap .put (name , i );
20
+ names .add (name );
21
+ }
22
+ int m = scanner .nextInt ();
23
+ for (int i = 0 ; i < m ; i ++) {
24
+ String first = scanner .next ();
25
+ String second = scanner .next ();
26
+ arrayList [hashMap .get (first )].add (hashMap .get (second ));
27
+ arrayList [hashMap .get (second )].add (hashMap .get (first ));
28
+ }
29
+ Set <String > first_ans = new HashSet <>();
30
+ Set <String > sec_ans = new HashSet <>();
31
+ for (int i = 0 ; i < n ; i ++) {
32
+ if (arr [i ] != 0 ) {
33
+ continue ;
34
+ }
35
+ Queue <Integer > queue = new LinkedList <>();
36
+ queue .add (i );
37
+ arr [i ] = 1 ;
38
+ first_ans .add (names .get (i ));
39
+ while (!queue .isEmpty ()) {
40
+ int curr = queue .poll ();
41
+ int color = arr [curr ];
42
+ for (int j = 0 ; j < arrayList [curr ].size (); j ++) {
43
+ if (arr [arrayList [curr ].get (j )] == 0 ) {
44
+ queue .add (arrayList [curr ].get (j ));
45
+ if (color == 1 ) {
46
+ arr [arrayList [curr ].get (j )] = 2 ;
47
+ sec_ans .add (names .get (arrayList [curr ].get (j )));
48
+ } else {
49
+ arr [arrayList [curr ].get (j )] = 1 ;
50
+ first_ans .add (names .get (arrayList [curr ].get (j )));
51
+ }
52
+ } else if (arr [arrayList [curr ].get (j )] == arr [curr ]) {
53
+ System .out .println ("impossible" );
54
+ System .exit (0 );
55
+ }
56
+ }
57
+ }
58
+ }
59
+ for (String name : first_ans ) {
60
+ System .out .print (name + " " );
61
+ }
62
+ System .out .println ();
63
+ for (String name : sec_ans ) {
64
+ System .out .print (name + " " );
65
+ }
66
+ }
67
+ }
0 commit comments