题目连接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=61
这道题目两种解法,费用流 或 DP。最近在搞图论,DP还没想到怎么做,不过费用流比DP效率高多了。。。
这道题目两种解法,费用流 或 DP。最近在搞图论,DP还没想到怎么做,不过费用流比DP效率高多了。。。
解析:首先问题是要从矩阵的G[1,1]到G[m,n]找出不相交的两条路径,使得他们的和最大。可以想到用最大费用最大流,注意是最大费用哦。从每个点[ i,j] 的左边邻点[ i,j-1 ] 和上边邻点[ i-1,j ]到点[ i,j ]建边,流量为1,费用为[ i,j ]的权值。但是这样是不是可能经过一个点多次? 答案是可能,所以要进行拆点,每个点拆成两个点,这两个点边的流量为1,费用为0,。点[1,1]和[m,n]拆开后流量为2(因为要找两条边),费用为0,接下来就是简单的费用流了。。。
好了,上代码:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
#define CLR(arr,v) memset(arr,v,sizeof(arr))
const int INF = 1<<29 ;
template<int MaxV,int MaxE>
class MinCostMaxFlow{
public:
void Clear(){
pos = 0;
CLR(h,-1); CLR(Flow,0);
}
void add(int u,int v,int f,int c){
num[pos] = v;
cap[pos] = f;
cost[pos] = c;
next[pos] = h[u];
h[u] = pos++;
num[pos] = u;
cap[pos] = 0;
cost[pos] = -c;
next[pos] = h[v];
h[v] = pos++;
}
int GetMinCostMaxFlow(int start,int end){
maxflow = 0; mincost = 0;
int cur;
while(SPFA(start,end)){
cur = end;
minflow = INF;
while(cur != start){
if(minflow > cap[ pre_e[cur] ] - Flow[ pre_e[cur] ])
minflow = cap[ pre_e[cur] ] - Flow[ pre_e[cur] ];
cur = pre_v[cur];
}
cur = end;
maxflow += minflow;
while(cur != start){
Flow[ pre_e[cur] ] += minflow;
Flow[ pre_e[cur]^1] -= minflow;
mincost += minflow * cost[ pre_e[cur] ];
cur = pre_v[cur];
}
}
return mincost;
}
private:
int h[MaxV],dis[MaxV],num[MaxE],cap[MaxE],cost[MaxE],Flow[MaxE],next[MaxE],pre_e[MaxV],pre_v[MaxV],Q[MaxV],InQ[MaxV],pos,minflow,mincost,maxflow;
bool SPFA(int s,int t){
CLR(dis,0);
CLR(InQ,0);
dis[s] = 1;
int head = 0,total = 0,cur;
Q[total++] = s;
while(head != total){
cur = Q[head++];
if(head >= MaxV) head = 0;
for(int i = h[cur];i != -1;i = next[i]){
if(cap[i] > Flow[i] && dis[cur] + cost[i] > dis[ num[i] ]){
dis[ num[i] ] = dis[cur] + cost[i];
pre_v[ num[i] ] = cur;
pre_e[ num[i] ] = i;
if(!InQ[ num[i] ])
{
if(total >= MaxV) total = 0;
InQ[ num[i] ] = true;
Q[total++] = num[i];
}
}
}
InQ[cur] = false;
}
return dis[t] > 1;
}
};
MinCostMaxFlow<5500,20050> g;
int main()
{
//freopen("1.txt","r",stdin);
//freopen("2.txt","w",stdout);
int T;
scanf("%d",&T);
while(T--)
{
g.Clear();
int m,n,u,U,v;
scanf("%d%d",&m,&n);
for(int i = 1;i <= m;++i)
{
for(int j = 1;j <= n;++j)
{
scanf("%d",&v);
u = (i-1)*n + j;
U = u + m*n;
if(i == 1 && j == 1)
g.add(u,U,2,0);
else if(i == m && j == n)
g.add(u,U,2,0);
else
g.add(u,U,1,0);
if(i-1 != 0)
g.add(U-n,u,1,v);
if(j-1 != 0)
g.add(U-1,u,1,v);
}
}
printf("%d\n",g.GetMinCostMaxFlow(1,m*n*2));
}
return 0;
}