Cod sursa(job #3323721)

Utilizator Nasa1004Ema Nicole Gheorghe Nasa1004 Data 19 noiembrie 2025 13:05:30
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.52 kb
#include <fstream>
#include <bitset>
#include <vector>
#include <queue>

using namespace std;
const int NMAX = 1000;
const int MMAX = 5000;

ifstream cin("maxflow.in");
ofstream cout("maxflow.in");

struct muchie {
    int nod;
    int cap;
    int flux;
    int pereche; ///spre muchia de adiacenta din celalalt vect
};
vector <vector <muchie>> v;
pair <int, int> tata[NMAX + 2]; ///tata si muchia
int n;

bitset <NMAX + 2> viz;
bool bfs() { ///cat pot sa mai pompez flux
    viz = 0;
    for(int i = 1; i <= n; i++) {
        tata[i].first = 0;
        tata[i].second = -1;
    }
    queue <int> q;
    viz[1] = 1;
    q.push(1);
    while(!q.empty()) {
        int now = q.front();
        q.pop();
        for(int i = 0; i < v[now].size(); i++) {
            muchie x = v[now][i];
            if(!viz[x.nod] && x.flux < x.cap) {
                tata[x.nod].first = now;
                tata[x.nod].second = i;
                viz[x.nod] = 1;
                q.push(x.nod);
            }
        }
    }
    return viz[n];
}

int recons(int nod, int minn) {
    while(tata[nod].first) { ///NU e 0
        minn = min(minn, v[tata[nod].first][tata[nod].second].cap - v[tata[nod].first][tata[nod].second].flux);
        nod = tata[nod].first;
        if(minn <= 0)
            return minn;
    }
    return minn;
}

void change(int a, int b, int id, int val) {
    v[a][id].flux += val;
    v[b][v[a][id].pereche].flux -= val;
}

void update(int nod, int add) {
    while(tata[nod].first) {
        change(tata[nod].first, nod, tata[nod].second, add);
        nod = tata[nod].first;
    }
}

int main() {
    int m;
    cin >> n >> m;
    v.resize(n + 1);
    for(int i = 1; i <= m; i++) {
        int a, b, cap;
        cin >> a >> b >> cap;
        v[a].push_back({b, cap, 0, -1});
        v[b].push_back({a, 0, 0, -1});
        v[a].back().pereche = v[b].size() - 1;
        v[b].back().pereche = v[a].size() - 1;
    }
    int ans = 0;
    while(bfs()) {
        for(int i = 0; i < v[n].size(); i++) { ///ne ducem pe muchii, dar basically pe alea inverse
            muchie x = v[n][i];
            if(viz[x.nod] && v[x.nod][x.pereche].flux < v[x.nod][x.pereche].cap) { ///inca se mai poate
                int add = recons(x.nod, v[x.nod][x.pereche].cap - v[x.nod][x.pereche].flux); ///cata cap mai avem
                if(add > 0) {
                    change(x.nod, n, x.pereche, add); ///iti schimbi muchia (nod, n)
                    update(x.nod, add);
                    ans += add;
                }
            }
        }
    }
    cout << ans;
    return 0;
}