[Link] https://www.acmicpc.net/problem/3648
In order for Karl to go to the next round
Method 1
Tarjan is DFS SCC => { x, -x } included in same scc || if(parent[1] > parent[-1]) => can’t be solved
Method 2
add edge before getting scc Node[-1].add(1); => if 1 => 1 => loop => can’t be solved
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
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
static StringBuilder sb = new StringBuilder();
static int n;
static Node[] nodes;
static int sccIdx = 1;
static int[] parent;
static boolean[] finished;
static boolean cantSolve = false;
static Stack<Integer> stack = new Stack<>();
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String line;
int[] arr;
while(true) {
if((line = br.readLine()) == null) break;
arr = Arrays.stream(line.split(" ")).mapToInt(Integer::parseInt).toArray();
n = arr[0];
int m = arr[1];
nodes = new Node[2 * n];
parent = new int[2 * n];
finished = new boolean[2 * n];
cantSolve = false;
sccIdx = 1;
for(int i = 0; i < 2 * n; i++) nodes[i] = new Node(rev(i));
for(int i = 0; i < m; i++) {
arr = getArr();
int a = arr[0], b = arr[1];
nodes[convert(a * -1)].list.add(b);
nodes[convert(b * -1)].list.add(a);
}
nodes[convert(-1)].list.add(1);
for(int i = 0; i < 2 * n; i++) {
if(parent[i] == 0) scc(i);
}
sb.append(cantSolve ? "no" : "yes").append("\n");
}
print(sb);
}
static int scc(int idx) {
int origVal = parent[idx] = sccIdx++;
stack.push(idx);
for(int v : nodes[idx].list) {
if(parent[convert(v)] == 0) parent[idx] = Math.min(parent[idx], scc(convert(v)));
else if(!finished[convert(v)]) parent[idx] = Math.min(parent[idx], parent[convert(v)]);
}
if(origVal == parent[idx]) {
HashSet<Integer> hm = new HashSet<>();
while(true) {
int pop = stack.pop();
int revVal = rev(pop);
finished[pop] = true;
if(hm.contains(revVal * (-1))) cantSolve = true;
hm.add(revVal);
if(idx == pop) break;
}
}
return parent[idx];
}
static int convert(int val) {
return val > 0 ? val - 1 : n - 1 - val;
}
static int rev(int idx) {
return idx < n ? idx + 1 : n - 1 - idx;
}
static class Node {
int idx;
ArrayList<Integer> list = new ArrayList<>();
public Node(int idx) { this.idx = idx; }
}
static int toi(String s) { return Integer.parseInt(s); }
static String[] getLine() throws IOException { return br.readLine().split(" "); }
static int[] getArr() throws IOException { return Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); }
static <T> void print(T s) { System.out.print(s); }
static <T> void println(T s) { System.out.println(s); }
}