Skip to content

Commit df9cd07

Browse files
committed
CF1971H 2-SAT
1 parent 4e6f66d commit df9cd07

File tree

2 files changed

+135
-0
lines changed

2 files changed

+135
-0
lines changed

main/1900-1999/1971H.go

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package main
2+
3+
import (
4+
"bufio"
5+
. "fmt"
6+
"io"
7+
)
8+
9+
// https://space.bilibili.com/206214
10+
func cf1971H(in io.Reader, _w io.Writer) {
11+
out := bufio.NewWriter(_w)
12+
defer out.Flush()
13+
14+
var T, n int
15+
o:
16+
for Fscan(in, &T); T > 0; T-- {
17+
Fscan(in, &n)
18+
a := [3][]int{}
19+
for i := range a {
20+
a[i] = make([]int, n)
21+
for j := range a[i] {
22+
Fscan(in, &a[i][j])
23+
}
24+
}
25+
26+
g := make([][]int, n*2)
27+
addEdge := func(x, a, y, b int) {
28+
if x < 0 {
29+
x = -x
30+
a ^= 1
31+
}
32+
if y < 0 {
33+
y = -y
34+
b ^= 1
35+
}
36+
v, w := x-1+a*n, y-1+b*n
37+
g[v] = append(g[v], w)
38+
}
39+
for j := 0; j < n; j++ {
40+
for p := 0; p < 3; p++ {
41+
for q := 0; q < 3; q++ {
42+
if q != p {
43+
addEdge(a[p][j], 0, a[q][j], 1)
44+
}
45+
}
46+
}
47+
}
48+
49+
sid := make([]int, len(g))
50+
dfn := make([]int, len(g))
51+
clock := 0
52+
st := []int{}
53+
inSt := make([]bool, len(g))
54+
var tarjan func(int) int
55+
tarjan = func(v int) int {
56+
clock++
57+
dfn[v] = clock
58+
lowV := clock
59+
st = append(st, v)
60+
inSt[v] = true
61+
for _, w := range g[v] {
62+
if dfn[w] == 0 {
63+
lowW := tarjan(w)
64+
lowV = min(lowV, lowW)
65+
} else if inSt[w] {
66+
lowV = min(lowV, dfn[w])
67+
}
68+
}
69+
if dfn[v] == lowV {
70+
for {
71+
w := st[len(st)-1]
72+
st = st[:len(st)-1]
73+
inSt[w] = false
74+
sid[w] = v
75+
if w == v {
76+
break
77+
}
78+
}
79+
}
80+
return lowV
81+
}
82+
for i, ts := range dfn {
83+
if ts == 0 {
84+
tarjan(i)
85+
}
86+
}
87+
for i, id := range sid[:n] {
88+
if id == sid[i+n] {
89+
Fprintln(out, "NO")
90+
continue o
91+
}
92+
}
93+
Fprintln(out, "YES")
94+
}
95+
}
96+
97+
//func main() { cf1971H(bufio.NewReader(os.Stdin), os.Stdout) }

main/1900-1999/1971H_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Generated by copypasta/template/generator_test.go
2+
package main
3+
4+
import (
5+
"github.com/EndlessCheng/codeforces-go/main/testutil"
6+
"testing"
7+
)
8+
9+
// https://codeforces.com/contest/1971/problem/H
10+
// https://codeforces.com/problemset/status/1971/problem/H
11+
func Test_cf1971H(t *testing.T) {
12+
testCases := [][2]string{
13+
{
14+
`4
15+
4
16+
1 -2 -3 -2
17+
-4 4 -1 -3
18+
1 2 -2 4
19+
2
20+
1 2
21+
-1 -2
22+
2 -2
23+
5
24+
1 2 3 4 5
25+
-2 3 -4 -5 -1
26+
3 -5 1 2 2
27+
6
28+
1 3 -6 2 5 2
29+
1 3 -2 -3 -6 -5
30+
-2 -1 -3 2 3 1`,
31+
`YES
32+
NO
33+
YES
34+
NO`,
35+
},
36+
}
37+
testutil.AssertEqualStringCase(t, testCases, 0, cf1971H)
38+
}

0 commit comments

Comments
 (0)