[Link] https://www.acmicpc.net/problem/11281
Tarjan is DFS
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
import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
static StringBuilder sb = new StringBuilder();
static Node[] nodes;
static int[] parent;
static int[] group;
static boolean[] finish;
static int sccIdx = 1, n, groupIdx = 1;
static boolean canSolve = true;
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();
int[] arr = getArr();
n = arr[0];
int m = arr[1];
nodes = new Node[2 * n];
for(int i = 0; i < 2 * n ; i++) nodes[i] = new Node(rev(i));
parent = new int[2 * n];
group = new int[2 * n];
finish = new boolean[2 * n];
for(int i = 0; i < m; i++) {
arr = getArr();
int a = arr[0], b = arr[1];
nodes[convert(-1 * a)].list.add(b);
nodes[convert(-1 * b)].list.add(a);
}
for(int i = 0; i < 2 * n; i++) {
if(parent[i] == 0) scc(i);
}
if(!canSolve) print(0);
else {
boolean[] groupSelected = new boolean[sccIdx];
sb.append("1\n");
for(int i = 1; i <= n; i++) {
int g1 = group[convert(i)], g2 = group[convert(i * -1)];
sb.append(g1 < g2 ? "1 " : "0 ");
}
print(sb);
}
}
static int scc(int idx) {
int origVal = parent[idx] = sccIdx++;
stack.push(idx);
for(int e : nodes[idx].list) {
if(parent[convert(e)] == 0) parent[idx] = Math.min(parent[idx], scc(convert(e)));
else if(!finish[convert(e)]) parent[idx] = Math.min(parent[idx], parent[convert(e)]);
}
if(origVal == parent[idx]) {
HashSet<Integer> hs = new HashSet<>();
while(true) {
int pop = stack.peek();
stack.pop();
int rev = rev(pop);
finish[pop] = true;
group[pop] = groupIdx;
if(hs.contains(rev * -1)) canSolve = false;
hs.add(rev);
if(pop == idx) break;
}
groupIdx++;
}
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 int abs(int nn) { return nn > 0 ? nn : -1 * nn; }
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); }
}