hdu 3667 Transportation 费用流

 

#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
const int N=500;
const int MAXE=20000000;
const int inf=1<<30;
int head[N],s,t,cnt,n,m,ans,k;
int d[N],pre[N];
bool vis[N];
int q[MAXE];
int flow;
struct Edge
{
    int u,v,c,w,next;
}edge[MAXE];

void addedge(int u,int v,int w,int c)
{
    edge[cnt].u=u;
    edge[cnt].v=v;
    edge[cnt].w=w;
    edge[cnt].c=c;
    edge[cnt].next=head[u];
    head[u]=cnt++;
    edge[cnt].v=u;
    edge[cnt].u=v;
    edge[cnt].w=-w;
    edge[cnt].c=0;
    edge[cnt].next=head[v];
    head[v]=cnt++;
}

int SPFA()
{
    int l,r;
    memset(pre,-1,sizeof(pre));
    memset(vis,0,sizeof(vis));
    for(int i=0;i<=t;i++) d[i]=inf;
    d[s]=0;
    l=0;r=0;
    q[r++]=s;
    vis[s]=1;
    while(l<r)
    {
        int u=q[l++];
        vis[u]=0;
        for(int j=head[u];j!=-1;j=edge[j].next)
        {
            int v=edge[j].v;
            if(edge[j].c>0&&d[u]+edge[j].w<d[v])
            {
                d[v]=d[u]+edge[j].w;
                pre[v]=j;
                if(!vis[v])
                {
                    vis[v]=1;
                    q[r++]=v;
                }
            }
        }
    }
    if(d[t]==inf)
        return 0;
    return 1;
}

void MCMF()
{
    flow=0;
    while(SPFA())
    {
        int u=t;
        int mini=inf;
        while(u!=s)
        {
            if(edge[pre[u]].c<mini)
                mini=edge[pre[u]].c;
                u=edge[pre[u]].u;
        }
        if(flow+mini>=k)
        {
            ans+=(k-flow)*d[t];
            flow=k;
            return ;
        }
        else
        {
            flow+=mini;
            ans+=d[t]*mini;
        }
        u=t;
        while(u!=s)
        {
            edge[pre[u]].c-=mini;
            edge[pre[u]^1].c+=mini;
            u=edge[pre[u]].u;
        }
    }
}

int main()
{
    while(scanf("%d%d%d",&n,&m,&k)!=EOF)
    {
		int i,j;
        s=1;t=n;cnt=0;
        for(i=0;i<=t+5;i++)
            head[i]=-1;
        for(i=1;i<=m;i++)
        {
            int u,v,cost,cap;
            scanf("%d%d%d%d",&u,&v,&cost,&cap);
            for(j=1;j<=cap;j++)
            {
                addedge(u,v,cost*(2*j-1),1);
                addedge(v,u,-cost*(2*j-1),0);
            }
        }
        ans=0;
        MCMF();
        if(flow==k)
            printf("%d\n",ans);
        else printf("-1\n");
    }
    return 0;
}


 

 

posted @ 2014-03-24 14:17  贝尔摩德  阅读(105)  评论(0编辑  收藏  举报