Cod sursa(job #2529863)

Utilizator memecoinMeme Coin memecoin Data 24 ianuarie 2020 08:02:18
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <fstream>
#include <string>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <math.h>
#include <set>
#include <map>
#include <string.h>
#include <queue>

using namespace std;

#ifdef DEBUG
string name = "data";
#else
string name = "maxflow";
#endif

ifstream fin(name + ".in");
ofstream fout(name + ".out");

#define MAXN 1001

int n, m;

int c[MAXN][MAXN];
int f[MAXN][MAXN];
int parent[MAXN];
vector<int> g[MAXN];

bool vis[MAXN];

bool bfs() {
    memset(vis, 0, sizeof(vis));
    
    queue<int> q;
    
    q.push(1);
    vis[1] = true;
    
    while (!q.empty()) {
        auto node = q.front();
        q.pop();
        
        for (auto x: g[node]) {
            if (c[node][x] > 0 && !vis[x] && c[node][x] != f[node][x]) {
                q.push(x);
                parent[x] = node;
                vis[x] = true;
            }
        }
    }
    
    return vis[n];
}

int main() {
    
    fin >> n >> m;
    
    for (int i = 0; i < m; ++i) {
        int x,y, val;
        fin >> x >> y >> val;
        c[x][y] = val;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    
    int flow = 0;

    while (bfs()) {
        int fmin = 0x3f3f3f3f;
        int node = n;
        
        while (node != 1) {
            int p = parent[node];
            
            fmin = min(fmin, c[p][node] - f[p][node]);
            
            node = p;
        }
        
        node = n;
        
        while (node != 1) {
            int p = parent[node];
            
            f[p][node] += fmin;
            f[node][p] -= fmin;
            
            node = p;
        }
        
        flow += fmin;
    }
    
    fout << flow;
    
    return 0;
}