hdu - 3549 基础最大流 EK

题意 :给你一个N个顶点M条边的有向图,要你求1号点到N号点的最大流.

注意重边。

链接 :hdu 3549

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define INF 0x3f3f3f3f

using namespace std;

const int inf = 0x3f3f3f3f;
const int maxn = 2005;

struct Edge {
    int v, nxt, w;
};

struct Node {
    int v, id;
};

int n, m, ecnt;
bool vis[maxn];
int head[maxn];
Node pre[maxn];
Edge edge[maxn];

void init() {
    ecnt = 0;
    memset(edge, 0, sizeof(edge));
    memset(head, -1, sizeof(head));
}

void addEdge(int u, int v, int w) {
    edge[ecnt].v = v;
    edge[ecnt].w = w;
    edge[ecnt].nxt = head[u];
    head[u] = ecnt++;
}

bool bfs(int s, int t) {
    queue  que;
    memset(vis, 0, sizeof(vis));
    memset(pre, -1, sizeof(pre));
    pre[s].v = s;
    vis[s] = true;
    que.push(s);
    while(!que.empty()) {
        int u = que.front();
        que.pop();
        for(int i = head[u]; i + 1; i = edge[i].nxt) {
            int v = edge[i].v;
            if(!vis[v] && edge[i].w) {
                pre[v].v = u;
                pre[v].id = i;
                vis[v] = true;
                if(v == t) return true;
                que.push(v);
            }
        }
    }
    return false;
}

int EK(int s, int t) {
    int ans = 0;
    while(bfs(s, t)) {
        int mi = INF;
        for(int i = t; i != s; i = pre[i].v) {
            mi = min(mi, edge[pre[i].id].w);
        }
        for(int i = t; i != s; i = pre[i].v) {
            edge[pre[i].id].w -= mi;
            edge[pre[i].id ^ 1].w += mi;
        }
        ans += mi;
    }
    return ans;
}

int main ()
{
    int t, kcase = 0;
    int N, M, E, k;
    char ch;
    cin >> t;
    while(t--) {
        scanf("%d %d", &N, &M);
    //while(~scanf("%d %d", &N, &M)) {
        init();
        int a, b, c;
        while(M--) {
            scanf("%d %d %d", &a, &b, &c);
            addEdge(a, b, c);
            addEdge(b, a, 0);
        };
        int ans = EK(1, N);
        printf("Case %d: %d\n", ++kcase, ans);
    }
    return 0;
}

你可能感兴趣的:(网络流)