hdu 1532 Drainage Ditches 增广路 ford

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const int N=1024;
const int inf=1<<24;
int abs(int x)
{
    if(x<0) return -x;
    else return x;
}

struct
{
    int c,f;
} g[N][N];

int n,m,u,v,c,f,i,j,ans;
int flag[N],p[N],a[N];
queue<int>q;
void ford()
{
    while(1)
    {
        memset(flag,0xff,sizeof(flag));
        memset(p,0xff,sizeof(p));
        memset(a,0xff,sizeof(a));
        a[0]=inf;
        p[0]=0;
        flag[0]=0;
        while(!q.empty()) q.pop();
        q.push(0);
        while(!q.empty()&&flag[n-1]==-1)
        {
            u=q.front();
            q.pop();
            for(i=0; i<n; i++)
            {
                if(flag[i]==-1)
                {
                    if(g[u][i].c<inf&&g[u][i].f<g[u][i].c)
                    {
                        flag[i]=0;
                        p[i]=u;
                        a[i]=min(a[u],g[u][i].c-g[u][i].f);
                        q.push(i);
                    }
                    else if(g[i][u].c<inf&&g[i][u].f>0)
                    {
                        flag[i]=0;
                        p[i]=-u;
                        a[i]=min(a[u],g[i][u].f);
                        q.push(i);
                    }
                }
            }
            flag[u]=1;
        }

        if(a[n-1]==0||flag[n-1]==-1) break;
        int k1=n-1,k2=abs(p[k1]);
        int add=a[n-1];
        //printf("%d\n",add);
        while(1)
        {
            if(g[k2][k1].f<inf)
                g[k2][k1].f+=add;
            else
                g[k1][k2].f-=add;
            if(k2==0) break;
            k1=k2;
            k2=abs(p[k2]);
        }
    }
    ans=0;
    for(i=0; i<n; i++)
        if(g[0][i].f<inf)
            ans+=g[0][i].f;

    printf("%d\n",ans);
}
int main()
{
    while(~scanf("%d%d",&m,&n))
    {
        for(i=0; i<n; i++)
            for(j=0; j<n; j++)
                g[i][j].c=g[i][j].f=inf;
        for(i=0; i<m; i++)
        {
            scanf("%d%d%d",&u,&v,&c);
            u--;
            v--;
            if(g[u][v].c==inf)
                g[u][v].c=c;
            else
                g[u][v].c+=c;
            g[u][v].f=0;
        }
        ford();
    }
    return 0;
}

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

posted @ 2015-08-11 23:01  xryz  阅读(111)  评论(0编辑  收藏  举报