Cod sursa(job #3328598)

Utilizator CVCiprianConstandache Vlad-Ciprian CVCiprian Data 9 decembrie 2025 13:14:29
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX = 1005;
const int INF = 2e9;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
int n, m;
int capacitate[NMAX][NMAX];
int flux[NMAX][NMAX];
int p[NMAX];
int vis[NMAX]; 
vector<int> G[NMAX];

int bfs(int s, int d){
    for(int i = 1; i <= n; i++){
        vis[i] = 0;
        p[i] = 0;
    }
    queue<int> q;
    q.push(s);
    vis[s] = 1;
    while(!q.empty()){
        int nod = q.front();
        q.pop();
        
        for(auto v : G[nod]){
            if(vis[v] == 0 && capacitate[nod][v] - flux[nod][v] > 0){
                vis[v] = 1;
                p[v] = nod; 
                q.push(v);
            }
        }
    }
    if(!vis[d]){
        return 0;
    }

    vector<int> path; 
    int x = d; 
    while( x != 0){
        path.push_back(x);
        x = p[x];
    }
    reverse(path.begin(), path.end());
    int flow = 1e9; 
    for(int i = 0; i< path.size() - 1; i++){
        int a = path[i];
        int b = path[i + 1];
        flow = min(flow, capacitate[a][b] - flux[a][b]);
    }

    for(int i = 0; i< path.size() - 1; i++){
        int a = path[i];
        int b = path[i + 1];
        flux[a][b] += flow; 
        flux[b][a] -= flow;
    }
    return flow; 
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y, c;
        fin >> x >> y >> c;
        capacitate[x][y] = c;
        G[x].push_back(y);
        G[y].push_back(x); 
    }

    int maxflow=0;
    while(true) {
        int flow=bfs(1,n);
        if(flow==0)
            break;
        maxflow+=flow;
    }
    
    fout << maxflow;
    
    return 0;
}