2013
12-12

# 方格取数(1)

3
75 15 21
75 15 28
34 70 5 

188

HDU_1565

#include<stdio.h>
#include<string.h>
#define MAXD 3000
#define MAXM 26000
#define INF 100000000
int N, SUM;
int first[MAXD], next[MAXM], u[MAXM], v[MAXM], flow[MAXM], e;
int s[MAXD], d[MAXD], q[MAXD], work[MAXD];
int dx[] = {-1, 1, 0, 0}, dy[] = {0, 0, -1, 1};
void add(int a, int b, int w)
{
u[e] = a;
v[e] = b;
flow[e] = w;
next[e] = first[a];
first[a] = e;
e ++;
}
int init()
{
int i, j, k, a;
if(scanf("%d", &N) != 1)
return 0;
memset(first, -1, sizeof(first));
e = SUM = 0;
for(i = 1; i <= N; i ++)
for(j = 1; j <= N; j ++)
{
scanf("%d", &a);
SUM += a;
if((i + j) % 2 == 0)
{
add(0, i * N + j, a);
add(i * N + j, 0, 0);
for(k = 0; k < 4; k ++)
{
int x = i + dx[k];
int y = j + dy[k];
if(x >= 1 && x <= N && y >= 1 && y <= N)
{
add(i * N + j, x * N + y, INF);
add(x * N + y, i * N + j, 0);
}
}
}
else
{
add(i * N + j, 1 , a);
add(1, i * N + j, 0);
}
}
return 1;
}
int bfs()
{
int i, j, rear;
memset(d, -1, sizeof(d));
d[0] = 0;
rear = 0;
q[rear ++] = 0;
for(i = 0; i < rear; i ++)
for(j = first[q[i]]; j != -1; j = next[j])
if(d[v[j]] == -1 && flow[j])
{
d[v[j]] = d[q[i]] + 1;
if(v[j] == 1)
return 1;
q[rear ++] = v[j];
}
return 0;
}
int dfs(int cur, int a)
{
if(cur == 1)
return a;
for(int &i = work[cur]; i != -1; i = next[i])
if(flow[i] && d[v[i]] == d[cur] + 1)
if(int t = dfs(v[i], a < flow[i] ? a : flow[i]))
{
flow[i] -= t;
flow[i ^ 1] += t;
return t;
}
return 0;
}
int dinic()
{
int res = 0, t;
while(bfs())
{
memcpy(work, first, sizeof(first));
while(t = dfs(0, INF))
res += t;
}
return res;
}
int main()
{
while(init())
{
int res = dinic();
printf("%d\n", SUM - res);
}
return 0;
}