Cod sursa(job #2901147)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 13 mai 2022 06:51:16
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

const string filename = "maxflow";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");

const int maxN = 1005, inf = 0x3f3f3f3f;
int n, m, s, d, pred[maxN], maxflux;
bool used[maxN];
struct muchie {
    int nxt, flux, cap;
}lm[5005];
vector <int> G[maxN];

bool bfs()
{
    queue <int> q;
    for(int i = 1; i <= n; i++)
        used[i] = 0;
    used[s] = 1;
    q.push(s);
    while(!q.empty())
    {
        int curr = q.front();
        q.pop();
        if(curr == d)
            return 1;
        for(int ind : G[curr])
        {
            if(lm[ind].cap > lm[ind].flux && !used[lm[ind].nxt])
            {
                pred[lm[ind].nxt] = ind;
                used[lm[ind].nxt] = 1;
                q.push(lm[ind].nxt);
            }
        }
    }
    return 0;
}

int main()
{
    fin >> n >> m;
    for(int i = 0; i < m; i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        lm[2 * i] = {y, 0, c};
        lm[2 * i + 1] = {x, 0, 0};
        G[x].push_back(2 * i);
        G[y].push_back(2 * i + 1);
    }
    s = 1, d = n;
    while(bfs())
    {
        int minflux = inf;
        for(int x = d; x != s; x = lm[pred[x]^1].nxt)
            minflux = min(minflux, lm[pred[x]].cap - lm[pred[x]].flux);
        for(int x = d; x != s; x = lm[pred[x]^1].nxt)
        {
            lm[pred[x]].flux += minflux;
            lm[pred[x]^1].flux -= minflux;
        }
        maxflux += minflux;
    }
    fout << maxflux;
    return 0;
}