1475: 方格取数
Time Limit: 5 Sec Memory Limit: 64 MB
Submit: 938 Solved: 465
Description
在一个n*n的方格里,每个格子里都有一个正整数。从中取出若干数,使得任意两个取出的数所在格子没有公共边,且取出的数的总和尽量大。
Input
第一行一个数n;(n<=30) 接下来n行每行n个数描述一个方阵
Output
仅一个数,即最大和
Sample Input
2
1 2
3 5
Sample Output
6
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#define clr(a) memset(a, 0, sizeof(a))
#define INF 2100000000
using namespace std;
const int N = 35;
const int M = 10005;
int x,n,sum,mp[N][N],S,T,ans;
int to[M],nxt[M],lj[N*N],w[M],cnt=-1;
queue <int> Q;
int d[N*N];
template <class T> inline void read(T &x) {
T flag = 1; x = 0;
char ch = (char)getchar();
while(ch < '0' || ch > '9') { if(ch == '-') flag = -1; ch = (char)getchar(); }
while(ch >= '0' && ch <= '9') { x = (x<<1)+(x<<3)+ch-'0'; ch = (char)getchar(); }
x *= flag;
}
void add(int f, int t, int p) {
to[++cnt] = t;
nxt[cnt] = lj[f];
w[lj[f] = cnt] = p;
to[++cnt] = f;
nxt[cnt] = lj[t];
lj[t] = cnt;
w[cnt] = 0;
}
bool bfs() {
clr(d); d[0] = 1; Q.push(0);
while(!Q.empty()) {
int x = Q.front(); Q.pop();
for(int i = lj[x]; i >= 0; i = nxt[i]) if(w[i] && !d[to[i]]) d[to[i]] = d[x]+1, Q.push(to[i]);
}
if(d[T]) return 1;
return 0;
}
int dfs(int x, int v) {
if(x == T || !v) return v;
int ret = 0;
for(int i = lj[x]; i >= 0; i = nxt[i]) if(d[to[i]] == d[x]+1) {
int f = dfs(to[i], min(w[i], v));
w[i] -= f;
w[i^1] += f;
v -= f;
ret += f;
if(!v) break;
}
return ret;
}
int get(int x, int y) { return (x-1)*n+y; }
int main() {
read(n);
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) read(mp[i][j]), sum += mp[i][j];
S = 0, T = n*n+1;
for(int i = 0; i <= T; i++) lj[i] = -1;
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++)
if(!((i+j)&1)) {
add(S, get(i, j), mp[i][j]);
if(i >= 2) add(get(i, j), get(i-1, j), INF);
if(j >= 2) add(get(i, j), get(i, j-1), INF);
} else {
add(get(i, j), T, mp[i][j]);
if(i >= 2) add(get(i-1, j), get(i, j), INF);
if(j >= 2) add(get(i, j-1), get(i, j), INF);
}
while(bfs()) ans += dfs(0, INF);
printf("%d",sum-ans);
}