BZOJ1475 方格取数 <黑白染色+最小割>

Problem

方格取数

Time Limit: 5Sec5 Sec
Memory Limit: 64MB64 MB

Description

在一个n×nn\times n的方格里,每个格子里都有一个正整数。从中取出若干数,使得任意两个取出的数所在格子没有公共边,且取出的数的总和尽量大。

Input

第一行一个数nnn30n\le 30),接下来nn行每行nn个数描述一个方阵

Output

仅一个数,即最大和

Sample Input

1
2
3
2
1 2
3 5

Sample Output

1
6

标签:黑白染色 最小割

Solution

将网格图黑白染色,同色格子间不会冲突。
建模:S黑格  容量valS\to 黑格\ \ 容量val白格T  容量val白格\to T\ \ 容量val黑格白格  容量黑格\to 白格\ \ 容量\infty
ans=总权值最小割ans = 总权值-最小割

Code

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
#include <bits/stdc++.h>
#define MAX_N 1000
#define INF 0x7f7f7f7f
using namespace std;
int nxt[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}, sum;
int n, m, s, t, cnt, id[35][35], a[MAX_N+5], d[MAX_N+5], pr[MAX_N+5];
struct node {int u, v, c, nxt;} E[MAX_N*MAX_N*2];
void init() {s = 0, t = m+1; memset(pr, -1, sizeof pr);}
void getID() {for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) id[i][j] = (i-1)*n+j;}
void insert(int u, int v, int c) {E[cnt].v = v, E[cnt].c = c, E[cnt].nxt = pr[u], pr[u] = cnt++;}
void addedge(int u, int v, int c) {insert(u, v, c), insert(v, u, 0);}
bool BFS() {
queue <int> que; que.push(s);
memset(d, -1, sizeof d), d[s] = 0;
while (!que.empty()) {
int u = que.front(); que.pop();
for (int i = pr[u]; ~i; i = E[i].nxt) {
int v = E[i].v, c = E[i].c;
if (!c || ~d[v]) continue;
d[v] = d[u]+1, que.push(v);
}
}
return ~d[t];
}
int DFS(int u, int flow) {
if (u == t) return flow;
int ret = 0;
for (int i = pr[u]; ~i; i = E[i].nxt) {
int v = E[i].v, c = E[i].c;
if (!c || d[v] != d[u]+1) continue;
int tmp = DFS(v, min(flow, c));
E[i].c -= tmp, E[i^1].c += tmp;
flow -= tmp, ret += tmp;
if (!flow) break;
}
if (!ret) d[u] = -1;
return ret;
}
int Dinic() {int ret = 0; while (BFS()) ret += DFS(s, INF); return ret;}
int main() {
scanf("%d", &n), m = n*n, getID(), init();
for (int i = 1; i <= m; i++) scanf("%d", a+i), sum += a[i];
for (int i = 1; i <= m; i++)
if ((i-1)%n%2 == (i-1)/n%2) addedge(s, i, a[i]);
else addedge(i, t, a[i]);
for (int i = 1; i <= m; i++) if ((i-1)%n%2 == (i-1)/n%2){
int x = (i-1)/n+1, y = (i-1)%n+1;
for (int j = 0; j < 4; j++) {
int nx = x+nxt[j][0], ny = y+nxt[j][1];
if (nx < 1 || nx > n || ny < 1 || ny > n) continue;
addedge(id[x][y], id[nx][ny], INF);
}
}
printf("%d", sum-Dinic());
return 0;
}