题目:http://www.lightoj.com/volume_showproblem.php?problem=1071
题意:给定一个n * m的矩阵,每个单元都有一个值,现在从左上走到右下再回到左上,中间不走重复的点,求所走单元的和的最大值
思路:这道题也算是费用流的经典题目了,不过用dp也能做。对于每个点,因为只能走一次,所以拆点连边做限制,容量为1,而起点终点要走两次,所以容量为2。把单元中的数字作为边的费用,这题是求最大和,所以可以先对费用取反,spfa能处理负权,求出来的最短路再取反就可以了。不过直接用spfa求最长路也行啊。。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 10010;
const int INF = 0x3f3f3f3f;
struct edge
{
int st, to, cap, cost, next;
}g[N*10];
int mpa[110][110], head[N*2], dis[N*2], pre[N*2];
int n, m, cnt, _case = 0;
bool used[N*2];
void add_edge(int v, int u, int cap, int cost)
{
g[cnt].st = v, g[cnt].to = u, g[cnt].cap = cap, g[cnt].cost = cost, g[cnt].next = head[v], head[v] = cnt++;
g[cnt].st = u, g[cnt].to = v, g[cnt].cap = 0, g[cnt].cost = -cost, g[cnt].next = head[u], head[u] = cnt++;
}
int mcmf(int s, int t, int f)
{
int res = 0;
while(f > 0)
{
memset(dis, 0x3f, sizeof dis);
memset(used, 0, sizeof used);
memset(pre, -1, sizeof pre);
queue<int> que;
dis[s] = 0;
used[s] = true;
que.push(s);
while(! que.empty())
{
int v = que.front(); que.pop();
for(int i = head[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(g[i].cap > 0 && dis[u] > dis[v] + g[i].cost)
{
dis[u] = dis[v] + g[i].cost;
pre[u] = i;
if(!used[u])
used[u] = true, que.push(u);
}
}
used[v] = false;
}
if(dis[t] == INF) return -1;
int d = f;
for(int i = pre[t]; i != -1; i = pre[g[i].st])
d = min(d, g[i].cap);
f -= d;
res += dis[t] * d;
for(int i = pre[t]; i != -1; i = pre[g[i].st])
g[i].cap -= d, g[i^1].cap += d;
}
return res;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
cnt = 0;
memset(head, -1, sizeof head);
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
scanf("%d", &mpa[i][j]);
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
{ //对每个点拆点连边,其中起点终点要走两次,所以容量为2,其余点只能走一次,容量为1
if((i == 0 && j == 0) || (i == n - 1 && j == m - 1))
add_edge(i * m + j, i * m + j + n * m, 2, 0);
else add_edge(i * m + j, i * m + j + n * m, 1, 0);
if(i != n - 1)
add_edge(i * m + j + n * m, (i+1) * m + j, 1, -mpa[i+1][j]);
if(j != m - 1)
add_edge(i * m + j + n * m, i * m + (j + 1), 1, -mpa[i][j+1]);
}
int res = -mcmf(0, 2 * n * m - 1, 2);
printf("Case %d: %d\n", ++_case, res + mpa[0][0] - mpa[n-1][m-1]);
}
return 0;
}