Cod sursa(job #2447050)

Utilizator CharacterMeCharacter Me CharacterMe Data 11 august 2019 21:20:30
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>
#define inf 2147483647
using namespace std;
int n, m, i, j, k, out;
int cmax[1001][1001], past[1001], flow[1001][1001];
bool vis[1001];
vector<int> graph[1001];
queue<int> q;

void read();
void solve();
void write();
bool bfs();
int main()
{
    read();
    solve();
    write();
    return 0;
}
void read(){
    freopen("maxflow.in", "r", stdin);
    scanf("%d%d", &n, &m);
    for(i=1; i<=m; ++i){
        int x, y, c;
        scanf("%d%d%d", &x, &y, &c);
        graph[x].push_back(y);
        graph[y].push_back(x);
        cmax[x][y]=c;
    }
    return;
}
void solve(){
    while(bfs()){
        for(auto node:graph[n]) if(vis[node] && cmax[node][n]!=flow[node][n]){
            past[n]=node;
            int now, elim=inf;
            for(now=n; now!=1; now=past[now]) elim=min(elim, cmax[past[now]][now]-flow[past[now]][now]);
            if(!elim) continue;
            for(now=n; now!=1; now=past[now]){
                flow[past[now]][now]+=elim;
                flow[now][past[now]]-=elim;
            }
            out+=elim;
        }
    }
    return;
}
void write(){
    freopen("maxflow.out", "w", stdout);
    printf("%d", out);
    return;
}
bool bfs(){
    while(!q.empty()) q.pop();
    for(i=1; i<=n; ++i) vis[i]=false, past[i]=0;
    q.push(1); vis[1]=true;
    while(!q.empty()){
        int node=q.front(); q.pop();
        if(node==n) continue;
        for(auto next:graph[node]){
            if(vis[next] || flow[node][next]==cmax[node][next]) continue;
            vis[next]=true;
            past[next]=node;
            q.push(next);
        }
    }
    return vis[n];
}