链接:

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=82835#problem/J

 

 

 

代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;

#define N 100005
#define INF 0x3fffffff

struct node {int v, flow, next;} a[N<<1];

int Layer[N], Head[N], cnt, n, m;

void Init()
{
    cnt = 0;
    memset(Head, -1, sizeof(Head));
}

void Add(int u, int v, int flow)
{
    a[cnt].v = v;
    a[cnt].flow = flow;
    a[cnt].next = Head[u];
    Head[u] = cnt++;
}

bool BFS(int Start, int End)
{
    queue<int>Q;
    Q.push(Start);

    memset(Layer, 0, sizeof(Layer));
    Layer[Start] = 1;

    while(Q.size())
    {
        int u = Q.front(); Q.pop();

        if(u==End) return true;

        for(int i=Head[u]; i!=-1; i=a[i].next)
        {
            int v = a[i].v;

            if(!Layer[v] && a[i].flow)
            {
                Layer[v] = Layer[u] + 1;
                Q.push(v);
            }
        }
    }
    return false;
}
int DFS(int u, int MaxFlow, int End)
{
    if(u==End) return MaxFlow;

    int uflow=0;

    for(int i=Head[u]; i!=-1; i=a[i].next)
    {
        int v = a[i].v;
        if(Layer[v]==Layer[u]+1 && a[i].flow)
        {
            int flow = min(a[i].flow, MaxFlow-uflow);
            flow = DFS(v, flow, End);

            a[i].flow -= flow;
            a[i^1].flow += flow;
            uflow += flow;

            if(uflow==MaxFlow) break;
        }
    }

    if(uflow==0) Layer[u] = 0;

    return uflow;
}
void Dinic(int Start, int End)
{
    int MaxFlow = 0;

    while(BFS(Start, End)==true)
      MaxFlow += DFS(Start, INF, End);
}

int main()
{
    while(scanf("%d%d", &n, &m), n+m)
    {
        int i, u, v, flow, x[N], y[N];

        Init();
        for(i=1; i<=m; i++)
        {
            scanf("%d%d%d", &u, &v, &flow);
            x[i] = u, y[i] = v;
            Add(u, v, flow);
            Add(v, u, flow);
        }

        Dinic(1, 2);

        for(i=1; i<=m; i++)
        {
            if((!Layer[x[i]] && Layer[y[i]]) || (Layer[x[i]] && !Layer[y[i]]))
                printf("%d %d\n", x[i], y[i]);
        }
        printf("\n");
    }
    return 0;
}

 

posted on 2015-08-14 11:10  栀蓝  阅读(182)  评论(0编辑  收藏  举报

levels of contents