Cod sursa(job #2470858)

Utilizator VodkaInTheJarGeorgi Petkov VodkaInTheJar Data 9 octombrie 2019 20:19:37
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1003;
const int INF = INT_MAX;

struct edge
{
    int to, cap, flow, rev;

    edge(int _to, int _cap, int _flow, int _rev)
    {
        to = _to, cap = _cap, flow = _flow, rev = _rev;
    }
};

int po[MAXN], dist[MAXN];
vector <edge> adj[MAXN];

void add_edge(int a, int b, int c)
{
    adj[a].push_back(edge(b, c, 0, adj[b].size()));
    adj[b].push_back(edge(a, 0, 0, adj[a].size()-1));
}

int n, m;
bool bfs()
{
    queue <int> q;
    memset(dist, -1, sizeof(dist));
    memset(po, 0, sizeof(po));

    dist[1] = 0;
    q.push(1);

    while (!q.empty())
    {
        int curr = q.front();
        q.pop();

        for (auto e: adj[curr])
            if (dist[e.to] == -1 && e.flow < e.cap)
            {
                dist[e.to] = dist[curr] + 1;

                q.push(e.to);
            }
    }

    return dist[n] != -1;
}

int dfs(int ver, int flow)
{
    if (ver == n)
        return flow;

    int sz = adj[ver].size();
    for (po[ver]; po[ver] < sz; po[ver]++)
    {
        edge &e = adj[ver][po[ver]];
        if (dist[e.to] == dist[ver] + 1 && e.flow < e.cap)
        {
            auto f = dfs(e.to, min(flow, e.cap - e.flow));

            e.flow += f;
            adj[e.to][e.rev].flow -= f;

            if (f > 0)
                return f;
        }
    }

    return 0;
}

int maxflow()
{
    int ans = 0;
    while (bfs())
        ans += dfs(1, n);

    return ans;
}

void read()
{
    cin >> n >> m;

    for (int i = 1; i <= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;

        add_edge(a, b, c);
    }
}

void solve()
{
    cout << maxflow() << endl;
}

int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    read();
    solve();
}