ACM/ICPC 之 最小割转网络流(POJ3469)

  重点:构图

 

//最小割转网络流
//邻接表+Dinic
//Time:5797Ms   Memory:6192K
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
#define MAXN 20005
#define MAXM 500005
#define INF 0x3f3f3f3f
struct Edge{
    int v, w, next;
    Edge(){}
    Edge(int vv, int ww, int nn):v(vv), w(ww), next(nn){}
}e[MAXM];
int n,m;
int s,t;
int h[MAXN], le;
int d[MAXN];
void add(int u, int v, int w)
{
    e[le] = Edge(v, w, h[u]);   h[u] = le++;
}
bool bfs()
{
    memset(d, -1, sizeof(d));
    queue<int> q;
    q.push(s);  d[s] = 0;
    while(!q.empty()){
        int cur = q.front();
        q.pop();
        for(int i = h[cur]; i != -1; i = e[i].next)
        {
            int v = e[i].v;
            if(d[v] == -1 && e[i].w)
            {
                d[v] = d[cur] + 1;
                if(v == t) return true;
                q.push(v);
            }
        }
    }
    return false;
}
int dfs(int x, int sum)
{
    if(x == t || sum == 0) return sum;
    int src = sum;
    for(int i = h[x]; i != -1; i = e[i].next)
    {
        int v = e[i].v;
        if(d[v] == d[x] + 1 && e[i].w){
            int tmp = dfs(v, min(e[i].w, sum));
            e[i].w -= tmp;
            e[i^1].w += tmp;
            sum -= tmp;
        }
    }
    return src - sum;
}
int Dinic()
{
    int maxFlow = 0;
    while(bfs())
        maxFlow += dfs(s, INF);
    return maxFlow;
}
int main()
{
    //freopen("in.txt", "r", stdin);
    memset(h,-1,sizeof(h));
    scanf("%d%d", &n,&m);
    s = 0;  t = n+1;
    for(int i = 1; i <= n; i++)
    {
        int a,b;
        scanf("%d%d", &a,&b);
        add(s, i, a);   add(i, s, 0);
        add(i, t, b);   add(t, i, 0);
    }
    for(int i = 1; i <= m; i++)
    {
        int u, v, w;
        scanf("%d%d%d", &u, &v, &w);
        add(u, v, w);   add(v, u, w);
    }
    printf("%d\n", Dinic());
    return 0;
}

 

posted @ 2016-07-28 18:28  文字失效  阅读(...)  评论(... 编辑 收藏