Cod sursa(job #2440532)

Utilizator AlexNeaguAlexandru AlexNeagu Data 18 iulie 2019 17:08:56
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>
#define nmax 1005
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
int Cost[nmax][nmax], Flux[nmax][nmax], From[nmax], visited[nmax], n, m, min_Edge;
vector < int > E[nmax];
int BFS()
{
    memset(visited, 0, sizeof(visited));
    queue < int > Q;
    Q.push(1);
    while (!Q.empty())
    {
        int node = Q.front();
        Q.pop();
        if (node == n) continue;
        for (auto it : E[node]) {
            if (visited[it] || Cost[node][it] == Flux[node][it]) continue;
            From[it] = node;
            visited[it] = 1;
            Q.push(it);
        }
    }
    return visited[n];
}
int main()
{
    in >> n >> m;
    while (m--)
    {
        int x, y, cost;
        in >> x >> y >> cost;
        Cost[x][y] = cost;
        E[x].push_back(y);
        E[y].push_back(x);
    }
    memset(Flux, 0, sizeof(Flux));
    int Max_Flux = 0;
    while (BFS()) {
        for (auto it : E[n]) {
            if (Flux[it][n] == Cost[it][n] || !visited[it]) continue;
            From[n] = it;
            min_Edge = 2e9;
            int adj = n;
            while (adj != 1) {
                if (Cost[From[adj]][adj] - Flux[From[adj]][adj] < min_Edge)
                    min_Edge = Cost[From[adj]][adj] - Flux[From[adj]][adj];
                    adj = From[adj];
            }
            if (min_Edge <= 0) continue;
            adj = n;
            while (adj != 1) {
                Flux[From[adj]][adj] += min_Edge;
                Flux[adj][From[adj]] -= min_Edge;
                adj = From[adj];
            }
            Max_Flux += min_Edge;
        }
    }
    return out << Max_Flux , 0;
}