HDU 1532 最大流

最大流模板题

注意反向边的意义。

#include<bits/stdc++.h>
using namespace std;
const int INF = 1e9;
const int MAXN = 301;
int ma[MAXN][MAXN],pre[MAXN];
int n,m;

int bfs(int s,int t){
    queue<int>q;
    int flow[MAXN];
    memset(flow,0,sizeof(flow));
    memset(pre,-1,sizeof(pre));
    pre[s] = 0;
    flow[s] = INF;
    q.push(s);
    while(!q.empty()){
        int u = q.front();
        q.pop();
        for(int i = 1;i <= m;i ++){
            if(ma[u][i] > 0 && pre[i] == -1){
                flow[i] = min(flow[u],ma[u][i]);
                pre[i] = u;
                q.push(i); 
            }
        }
    }
    if(pre[t] == -1) return -1;
    else return flow[t];
} 

int maxflow(int s,int t){
    int Maxflow = 0;
    while(1){
        int flow = bfs(s,t);
        if(flow == -1) break;
        int cur = t;
        while(cur != s){
            ma[pre[cur]][cur] -= flow;
            ma[cur][pre[cur]] += flow;
            cur = pre[cur];
        }
        Maxflow += flow;
    }
    return Maxflow;
}

void solve(){
    memset(ma,0,sizeof(ma));
    for(int i = 1;i <= n;i ++){
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        ma[u][v] += w;
    }
    printf("%d\n",maxflow(1,m));
}
int main(){
    while(~scanf("%d%d",&n,&m)) solve();
    return 0;
}
View Code

猜你喜欢

转载自www.cnblogs.com/cgold/p/12237617.html
今日推荐