Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P2962 [USACO09NOV]Lights G

P2962 [USACO09NOV]Lights G

直接上高斯消元。

考虑如何找到最优解,高斯消元后直接暴搜,对于自由元,枚举是否选择;否则如果不是自由元,增加答案。

查看代码
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
#include <cstdio>
#include <bitset>
using namespace std;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
flag && (x = ~x + 1);
}
template <class Type>
void write(Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar(x % 10 + '0');
}
const int N = 40;
bool vis[N];
int n, m, ans;
bitset<N> A[N];
void dfs (int x, int s)
{
if (s >= ans)
return;
if (!x)
return ans = s, void();
if (A[x][x])
{
bool v = A[x][0];
for (int i = x + 1; i <= n; i++)
A[x][i] && (v ^= vis[i]);
dfs(x - 1, s + v);
}
else
{
dfs(x - 1, s);
vis[x] = true;
dfs(x - 1, s + 1);
vis[x] = false;
}
}
void Gauss()
{
for (int k = 1; k <= n; k++)
{
int t = k;
while (t <= n && !A[t][k])
t++;
if (t > n) // No Solution
continue;
swap(A[t], A[k]);
for (int i = 1; i <= n; i++)
i ^ k && A[i][k] && (A[i] ^= A[k], 0);
}
}
int main ()
{
read(n), read(m);
for (int a, b; m; m--)
{
read(a), read(b);
A[a][b] = A[b][a] = 1;
}
for (int i = 1; i <= n; i++)
{
A[i][i] = 1;
A[i][0] = 1;
}
Gauss();
ans = n;
dfs(n, 0);
write(ans);
return 0;
}

另外一种双向搜索的做法,将第一次搜索的中间状态塞进一个 map 里面,第二次再来查询。

查看代码
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

#include <cstdio>
#include <map>
using namespace std;
typedef long long L;
const int N = 35;
int n, m, ans = N;
L ed, op[N];
map <L, int> f;
void chkmin (int &x, int k) { if (k < x) x = k; }
void dfs (int x, int y, L s, int t)
{
if (x == y)
{
if (y == n)
{
if (f.count(s))
chkmin(ans, f[s] + t);
}
else
{
if (f.count(s)) chkmin(f[s], t);
else f[s] = t;
}
return;
}
dfs(x + 1, y, s ^ op[x], t + 1);
dfs(x + 1, y, s, t);
}
int main()
{
scanf("%d%d", &n, &m);
ed = (1ll << n) - 1;
for (int i = 0; i < n; ++i)
op[i] |= 1ll << i;
for (int i = 1, a, b; i <= m; ++i)
{
scanf("%d%d", &a, &b);
--a, --b;
op[a] |= 1ll << b;
op[b] |= 1ll << a;
}
// for (int i = 0; i < n; ++i)
// printf("%lld\n", op[i]);
// return 0;
dfs(0, n >> 1, 0, 0);
dfs(n >> 1, n, ed, 0);
printf("%d", ans);
return 0;
}