poj 3422 Kaka's Matrix Travels 最小费最大流

输入的时候没有取反,一直ole。
这里也是用到拆点,将一个点拆成p和q,这两个之间连接两条路,一条cap=1和cost=矩阵上的值,另一条为cap=k和cost=0。在将0和2*n *n+1看成源点和汇点。

#include<stdio.h>
#include<string.h>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int N=10000+5;

struct Edge
{
    int from,to,cap,flow,cost;
};
vector<Edge>edges;
vector<int>G[N];
int n,k,inq[N],d[N],p[N],a[N],c;

void AddEdge(int from,int to ,int cap,int cost)
{
    Edge tp;
    tp.from=from,tp.to=to,tp.cap=cap,tp.flow=0,tp.cost=cost;
    edges.push_back(tp);
    tp.from=to,tp.to=from,tp.cap=0,tp.flow=0,tp.cost=-cost;
    edges.push_back(tp);
    int g=edges.size();
    G[from].push_back(g-2);
    G[to].push_back(g-1);
}

int BellmanFord(int s,int t,int &flow, int &cost)
{
    int i,j,u;
    for(i=0; i<=t; i++) d[i]=-1;
    memset(inq,0,sizeof(inq));
    d[s]=0;
    inq[s]=1;
    p[s]=0;
    a[s]=0xfffffff;
    queue<int>Q;
    Q.push(s);
    while(!Q.empty())
    {
        u=Q.front();
        Q.pop();
        inq[u]=0;
        for(i=0; i<G[u].size(); i++)
        {
            Edge &e=edges[G[u][i]];
            if(e.cap>e.flow&&d[e.to]<d[u]+e.cost)
            {
                d[e.to]=d[u]+e.cost;
                p[e.to]=G[u][i];
                a[e.to]=min(a[u],e.cap-e.flow);
                if(!inq[e.to])
                {
                    Q.push(e.to);
                    inq[e.to]=1;
                }
            }
        }
    }
    if(d[t]==-1) return 0;
    flow+=a[t];
    cost+=d[t]*a[t];
    u=t;
    while(u!=s)
    {
        edges[p[u]].flow+=a[t];
        edges[p[u]^1].flow-=a[t];
        u=edges[p[u]].from;
    }
    return 1;
}

int Mincost(int s,int t)
{
    int flow=0,cost=0;
    while(BellmanFord(s,t,flow,cost));
    return cost;
}

int main()
{
    int i,j;
    while(~scanf("%d%d",&n,&k))
    {
        for(i=0; i<=2*n*+1; i++) G[i].clear();
        edges.clear();
        for(i=1; i<=n; i++)
            for(j=1; j<=n; j++)
            {
                scanf("%d",&c);
                int p=(i-1)*n+j;
                int q=p+n*n;
                AddEdge(p,q,1,c);
                AddEdge(p,q,k,0);
                if(i!=n) AddEdge(q,p+n,k,0);//下
                if(j!=n) AddEdge(q,p+1,k,0);//右
            }
        AddEdge(0,1,k,0);
        AddEdge(2*n*n,2*n*n+1,k,0);
        int ans=Mincost(0,2*n*n+1);
        printf("%d\n",ans);
    }
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/

posted @ 2015-08-19 15:38  xryz  阅读(92)  评论(0编辑  收藏  举报