题目背景
none!
题目描述
在一个有 m*n 个方格的棋盘中,每个方格中有一个正整数。现要从方格中取数,使任意 2 个数所在方格没有公共边,且取出的数的总和最大。试设计一个满足要求的取数算法。对于给定的方格棋盘,按照取数要求编程找出总和最大的数。
输入格式
第 1 行有 2 个正整数 m 和 n,分别表示棋盘的行数和列数。接下来的 m 行,每行有 n 个正整数,表示棋盘方格中的数。
输出格式
程序运行结束时,将取数的最大总和输出
输入输出样例
输入 #1复制
3 3
1 2 3
3 2 3
2 3 1
输出 #1复制
11
说明/提示
m,n<=100
题解
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> p;
const double pi = acos(-1.0);
const int inf = 0x3f3f3f3f;
const int maxn = 1e4 + 10;
const int dx[4] = { 0, 0, 1, -1 };
const int dy[4] = { 1, -1, 0, 0 };
int cnt, head[maxn], dep[maxn], cur[maxn];
struct edge { int to, flow, next; } e[maxn << 2];
template<typename T = int>
inline const T read()
{
T x = 0, f = 1; char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + ch - '0'; ch = getchar(); }
return x * f;
}
template<typename T>
inline void write(T x)
{
if (x < 0) { putchar('-'); x = -x; }
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
void addEdge(int u, int v, int w)
{
e[cnt].to = v;
e[cnt].flow = w;
e[cnt].next = head[u];
head[u] = cnt++;
}
bool bfs(int s, int t)
{
queue<int> q;
memset(dep, -1, sizeof(dep));
dep[s] = 0;
q.push(s);
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = head[u]; ~i; i = e[i].next)
{
int v = e[i].to;
if (dep[v] == -1 && e[i].flow)
{
q.push(v);
dep[v] = dep[u] + 1;
}
}
}
return ~dep[t];
}
int dfs(int u, int t, int rflow)
{
if (u == t) return rflow;
int res = 0;
for (int i = cur[u]; ~i && rflow; i = e[i].next)
{
int v = e[i].to;
if (dep[v] != dep[u] + 1 || !e[i].flow) continue;
cur[u] = i;
int flow = dfs(v, t, min(e[i].flow, rflow));
e[i].flow -= flow;
e[i ^ 1].flow += flow;
rflow -= flow;
res += flow;
}
if (!res) dep[u] = -1;
return res;
}
int dinic(int s, int t)
{
int res = 0;
while (bfs(s, t))
{
memcpy(cur, head, sizeof(head));
res += dfs(s, t, inf);
}
return res;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("input.txt", "r", stdin);
#endif
int n = read(), m = read(), sum = 0;
memset(head, -1, sizeof(head));
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
int u = (i - 1) * m + j, w = read();
sum += w;
if ((i + j) & 1)
{
addEdge(0, u, w);
addEdge(u, 0, w);
for (int k = 0; k < 4; k++)
{
int x = i + dx[k], y = j + dy[k];
int v = (x - 1) * m + y;
if (x >= 1 && x <= n && y >= 1 && y <= m)
{
addEdge(u, v, inf);
addEdge(v, u, 0);
}
}
}
else
{
addEdge(u, n * m + 1, w);
addEdge(n * m + 1, u, 0);
}
}
}
printf("%d\n", sum - dinic(0, n * m + 1));
return 0;
}