POJ-1273 网络流...

题意:很裸,M和N的顺序别搞错了。

代码如下:

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

int N, M;
const int INF = 0x3f3f3f3f;

struct Edge {
    int v, c, next;    
}e[500];

int idx, head[205];
int level[205];
int front, tail, que[205];

void insert(int a, int b, int c) {
    e[idx].v = b, e[idx].c = c;
    e[idx].next = head[a];
    head[a] = idx++;    
}

bool bfs() {
    memset(level, 0xff, sizeof (level));
    level[1] = 0;
    front = tail = 0;
    que[tail++] = 1;
    while (front != tail) {
        int u = que[front++];
        for (int i = head[u]; i != -1; i = e[i].next) {
            if (!(~level[e[i].v]) && e[i].c) {
                level[e[i].v] = level[u] + 1;
                if (e[i].v == N) return true;
                que[tail++] = e[i].v;
            }
        }
    }
    return ~level[N];
}

int dfs(int u, int sup) {
    if (u == N) return sup;
    int tf = 0, f;
    for (int i = head[u]; i != -1; i = e[i].next) {
        if (level[u]+1==level[e[i].v] && e[i].c && (f = dfs(e[i].v, min(e[i].c, sup-tf)))) {
            tf += f;
            e[i].c -= f, e[i^1].c += f;
            if (tf == sup) return sup;
        }
    }
    if (!tf) level[u] = -1;
    return tf;
}

int dinic() {
    int ret = 0;
    while (bfs()) {
        ret += dfs(1, INF);    
    }
    return ret;
}

int main() {
    while (scanf("%d %d", &M, &N) != EOF) {
        idx = 0;
        int x, y, z;
        memset(head, 0xff, sizeof (head));
        for (int i = 1; i <= M; ++i) {
            scanf("%d %d %d", &x, &y, &z);
            insert(x, y, z);
            insert(y, x, 0);
        }
        printf("%d\n", dinic());
    }
    return 0;    
} 

 

posted @ 2013-04-30 14:56  沐阳  阅读(204)  评论(0编辑  收藏  举报