Home BOJ. 2-SAT - 3 (11280)
Post
Cancel

BOJ. 2-SAT - 3 (11280)

[Link] https://www.acmicpc.net/problem/11280


IDEA

(N U M) = true <=> (!N => M) || (M => !N)
[ 1~n, -1 ~ -n ] => SCC => (a => b => c … => (-a)) => can’t be solved(When SCC includes x and -x)

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
import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static StringBuilder sb = new StringBuilder();
	static int sccIdx = 1;
	static Stack<Integer> stack = new Stack<>();
	static int[] parent;
	static boolean[] finished;
	static boolean cantSolve = false;
	static Node[] nodes;
	static int n;
	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];
		finished = new boolean[2 * n];
		parent = new int[2 * n];

		for(int i = 1; i <=n; i++) nodes[convert(i)] = new Node(i);
		for(int i = -n; i <= -1; i++) nodes[convert(i)] = new Node(i);

		for(int i = 0; i < m; i++) {
			arr = getArr();
			int a = arr[0], b = arr[1], bit1 = a > 0 ? 1 : -1, bit2 = b > 0 ? 1 : -1;
			nodes[convert((-1) * a)].list.add(b);
			nodes[convert((-1) * b)].list.add(a);
		}

		for(int j = 0; j < 2 * n ; j++) {
			if(parent[j] == 0) scc(j);
			if(cantSolve) {
				print(0);
				return;
			}
		}
		print(1);
	}

	//0 ~ (n-1) : 1 ~(n) || n ~ (2n - 1): -1 ~ -n
	static int convert(int idx) { return idx > 0 ? idx - 1 : n - 1 - idx; }
	static int rev(int idx) { return idx < n ? idx + 1 : n - 1 - idx; }

	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(finished[convert(e)] == false) parent[idx] = Math.min(parent[idx], parent[convert(e)]);
		}

		if(origVal == parent[idx]) {
			HashSet<Integer> hs = new HashSet<>();
			while(true) {
				int pop = stack.pop();
				int rev = rev(pop);
				if(hs.contains((-1) * rev)) cantSolve = true;
				hs.add(rev);
				finished[pop] = true;
				if(pop == idx) break;
			}
		}

		return parent[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); }
}
This post is licensed under CC BY 4.0 by the author.