-
Notifications
You must be signed in to change notification settings - Fork 31
/
MaxIndependentSet.go
140 lines (123 loc) · 2.13 KB
/
MaxIndependentSet.go
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
// 无向图最大独立集(独立集是指图 G 中两两互不相邻的顶点构成的集合)
// n<=40
package main
import (
"bufio"
"fmt"
"os"
)
func maxIndepentSet(n int, edges [][]int) []int {
adjList := make([][]int, n)
deg := make([]int, n)
for _, e := range edges {
u, v := e[0], e[1]
adjList[u] = append(adjList[u], v)
adjList[v] = append(adjList[v], u)
deg[u]++
deg[v]++
}
used, dead := make([]int, n), make([]int, n)
pre, ans := []int{}, []int{}
res, count, alive := 0, 0, n
var dfs func()
dfs = func() {
if count+alive <= res {
return
}
v := -1
for i := 0; i < n; i++ {
if used[i] != 0 || dead[i] != 0 {
continue
}
if deg[i] <= 1 {
v = i
break
}
if v < 0 || deg[v] < deg[i] {
v = i
}
}
if v < 0 {
return
}
if deg[v] != 1 {
dead[v] = 1
alive--
for _, u := range adjList[v] {
deg[u]--
}
dfs()
dead[v] = 0
alive++
for _, u := range adjList[v] {
deg[u]++
}
}
used[v] = 1
alive--
for _, u := range adjList[v] {
if dead[u] == 0 {
dead[u]++
if used[u] == 0 {
alive--
}
} else {
dead[u]++
}
}
count++
if count > res {
pre = append(pre[:0:0], used...)
}
res = max(res, count)
dfs()
used[v] = 0
alive++
for _, u := range adjList[v] {
dead[u]--
if dead[u] == 0 {
if used[u] == 0 {
alive++
}
}
}
count--
}
dfs()
for i := 0; i < n; i++ {
if pre[i] != 0 {
ans = append(ans, i)
}
}
return ans
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func main() {
in := bufio.NewReader(os.Stdin)
out := bufio.NewWriter(os.Stdout)
defer out.Flush()
var n, m int
fmt.Fscan(in, &n, &m)
edges := make([][]int, 0, m)
for i := 0; i < m; i++ {
var u, v int
fmt.Fscan(in, &u, &v)
edges = append(edges, []int{u, v})
}
res := maxIndepentSet(n, edges)
fmt.Fprintln(out, len(res))
for _, v := range res {
fmt.Fprint(out, v, " ")
}
}