題目背景
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;
}