Cod sursa(job #2270065)

Utilizator EuAlexOtaku Hikikomori EuAlex Data 27 octombrie 2018 02:45:37
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
 
using namespace std;
 
const int nmax = 1000;
const int inf = 2000000000;
 
struct Muchie {
    int to;
    int rev;
    int cap;
    int flow;
};
 
vector <Muchie> g[1 + nmax];
int cap[1 + nmax][1 + nmax];
int n, m, sursa, destinatie;
int dist[1 + nmax], rem[1 + nmax];
queue <int> q;
 
int bfs() {
    fill(dist + 1, dist + n + 1, -1);
    q.push(sursa);
    dist[sursa] = 0;
 
    while(!q.empty()) {
        int from;
        from = q.front();
 
        for(int k = 0; k < g[from].size(); ++ k) {
            Muchie &e = g[from][k];
 
            if(dist[e.to] == -1 && e.flow < e.cap) {
                dist[e.to] = dist[from] + 1;
                q.push(e.to);
            }
        }
 
        q.pop();
    }
 
    return (dist[destinatie] > -1);
}
 
int minim(int a, int b) {
    if(a > b) {
        return b;
    }
    return a;
}
 
int dfs(int from, int minflux) {
    if(from == destinatie) {
        return minflux;
    } else {
        for(int k = rem[from]; k < g[from].size(); ++ k) {
            Muchie &e = g[from][k];
 
            if(dist[e.to] == dist[from] + 1) {
                int adaug = dfs(e.to, minim(minflux, e.cap - e.flow));
 
                if(adaug > 0) {
                    e.flow += adaug;
                    g[e.to][e.rev].flow -= adaug;
                    rem[from] = k;
                    return adaug;
                }
            }
        }
        return 0;
    }
}
 
int maxflow() {
    int raspuns = 0, adaug;
 
    while(bfs() == 1) {
        fill(rem + 1, rem + n + 1, 0);
        do{
            adaug = dfs(sursa, inf);
            raspuns += adaug;
        }while(adaug > 0);
    }
 
    return raspuns;
}
 
int main() {
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
 
    scanf("%d%d", &n, &m);
    sursa = 1;
    destinatie = n;
 
    for(int i = 1; i <= m; ++ i) {
        int x, y, c;
        scanf("%d%d%d", &x, &y, &c);
        cap[x][y] = c;
    }
 
    for(int i = 1; i <= n; ++ i) {
        for(int j = i + 1; j <= n; ++ j) {
            if(cap[i][j] != 0 || cap[j][i] != 0) {
                g[i].push_back({j, g[j].size(), cap[i][j], 0});
                g[j].push_back({i, g[i].size() - 1, cap[j][i], 0});
            }
        }
    }
 
    printf("%d", maxflow());
 
    return 0;
}