Cod sursa(job #3328909)

Utilizator busoistefanBusoi Radulescu Stefan busoistefan Data 11 decembrie 2025 09:04:04
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("maxflow.in");
ofstream g("maxflow.out");

struct vecini {
    int node;
    int currentflow;
    int reverseNode;
};
vector<vecini> v[1006];
int depth[1006];
int n,m;
int src=1;
int dest;
void BFS() {
    queue<int> q;
    q.push(src);

    for (int i=1;i<=n;i++) {
        depth[i]=-1;
    }
    depth[src]=0;
    while(!q.empty()) {
        int x=q.front();
        q.pop();
        for(auto nod:v[x]) {
            if (nod.node==dest) {
                continue;
            }
            if (nod.currentflow!=0) {
                if (depth[nod.node]==-1) {
                    depth[nod.node]=depth[x]+1;
                    q.push(nod.node);
                }
            }
        }
    }
}

int DFS(int node,int possible=1000000) {
    int ans=0;

    for (auto& vec:v[node]) {
        if (vec.node==dest) {
            int flow=min(possible,vec.currentflow);
            ans+=flow;
            possible-=flow;
            vec.currentflow-=flow;
        }
        if (depth[vec.node]==depth[node]+1) {
            int flow=DFS(vec.node,min(possible,vec.currentflow));
            ans+=flow;
            possible-=flow;
            vec.currentflow-=flow;
            v[vec.node][ vec.reverseNode].currentflow+=flow;
        }
    }
    return ans;
}
int main() {
    f>>n>>m;
    for(int i=0;i<m;i++) {
        int x,y,cost;
        f>>x>>y>>cost;
        v[y].push_back({x,0,(int)v[x].size()});
        v[x].push_back({y,cost,(int)v[y].size()-1});
    }
    dest=n;
    int ans=0;
    while(1) {
        BFS();
        int x=DFS(src,10000000);
        if (x==0) {
            break;
        }
        ans+=x;
    }
    g<<ans;
}