BNUOJ 1392 Drainage Ditches

和前面那个POJ 1273是一样的,这里用的是Dinic算法,所以当做一个模板保存一下。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define INF 0x7fffffff
using namespace std;
int val[300][300];
int lev[300];
int n,m;
bool bfs()
{
    int u,v;
    memset(lev,-1,sizeof(lev));
    lev[1]=0;
    queue<int> q;
    while (!q.empty())
        q.pop();
    q.push(1);
    while (!q.empty())
    {
        u=q.front();
        q.pop();
        for (v=1; v<=n; v++)
        {
            if (val[u][v] > 0 && lev[v] < 0)
            {
                lev[v]=lev[u]+1;
                q.push(v);
            }
        }
    }
    return lev[n] != -1;
}
int dfs(int u,int flow)
{
    int v,t;
    if (u == n)
        return flow;
    for (v=1; v<=n; v++)
    {
        if (val[u][v] != 0 && lev[v] == lev[u]+1 && (t=dfs(v,min(flow,val[u][v]))))
        {
            val[u][v]-=t;
            val[v][u]+=t;
            return t;
        }
    }
    return 0;
}
int dinic()
{
    int ans,t;
    ans=0;
    while(bfs() == true)
    {
        while(1)
        {
            t=dfs(1,INF);
            if (t == 0)
                break;
            ans+=t;
        }
    }
    return ans;
}
int main()
{
    int t1,t2,t3,i,j;
    while (scanf("%d%d",&m,&n) != EOF)
    {
        memset(val,0,sizeof(val));
        for (i=0; i<m; i++)
        {
            scanf("%d%d%d",&t1,&t2,&t3);
            val[t1][t2]+=t3;
        }
        printf("%d\n",dinic());
    }
}


你可能感兴趣的:(BNUOJ 1392 Drainage Ditches)