Cod sursa(job #3293347)

Utilizator elisa.ipateElisa Ipate elisa.ipate Data 11 aprilie 2025 15:21:46
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
using namespace std;
const int nmax = 1001;
const int inf = 1e9;
queue <int> q;
vector <int> parent;
int minn[nmax], i_edge[nmax];
struct info{
    int adj, max_flow, cur_flow, i;
};
vector <info> edges[nmax];
int ans;
bool bfs( int S, int D, int n ) {
    int vf;
    //init
    while( !q.empty() )
        q.pop();
    parent.clear();
    parent.resize(n + 1 );
    minn[S] = inf;
    parent[S] = S;
    q.push( S );

    while( !q.empty() ) {
        vf = q.front();
        q.pop();
        if( vf == D )
            return true;
        for( int i = 0; i < edges[vf].size(); i++ ) {
            info aux = edges[vf][i];
            if( aux.cur_flow == aux.max_flow || parent[aux.adj] != 0 )
                continue;
            parent[aux.adj] = vf;
            minn[aux.adj] = min( minn[vf], aux.max_flow - aux.cur_flow );
            i_edge[aux.adj] = i;
            q.push(aux.adj );
        }
    }
    return false;
}

void solve( int S, int D, int n ) {
    int vf, flow;
    while( bfs( S, D, n) ) {
        vf = D;
        flow = minn[D];
        ans += flow;
        while( vf != S ) {
            // din muchia parent[vf] si vf, adaug flow
            info aux = edges[parent[vf]][i_edge[vf]];
            edges[parent[vf]][i_edge[vf]].cur_flow += flow;
            edges[vf][aux.i].cur_flow -= flow;
            vf = parent[vf];
        }
    }
}

int main() {
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");
    int n, m, x, y, c;
    info aux;
    cin >> n >> m;
    for( int i = 0; i < m; i++ ) {
        cin >> x >> y >> c;
        aux.adj = y;
        aux.cur_flow = 0;
        aux.max_flow = c;
        aux.i = edges[y].size();
        edges[x].push_back(aux);
        aux.adj = x;
        aux.cur_flow = 0;
        aux.max_flow = 0;
        aux.i = edges[x].size() - 1;
        edges[y].push_back(aux);
    }
    solve( 1, n, n );
    cout << ans << "\n";
}