Cod sursa(job #3319420)

Utilizator stanciuvalentinStanciu-Tivlea Valentin Gabriel stanciuvalentin Data 1 noiembrie 2025 12:08:19
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,x,y,z,sflow, cap[1020][1020], viz[1020], flow[1020][1020], tata[1020];
vector <int> edges[1020];
queue <int> q;

bool bfs(int sursa, int destinatie){
    while(!q.empty())
        q.pop();
    memset(viz, 0, sizeof(viz));
    q.push(sursa);
    viz[sursa]=1;
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(auto y:edges[x])
        {
            if(viz[y]==0 and cap[x][y]!=flow[x][y])
            {
                viz[y]=1;
                tata[y]=x;
                if(y==destinatie)
                    return 1;
                q.push(y);
            }
        }
    }
    return 0;
}

int main()
{
    f>>n>>m;
    for(int i=1; i<=m; i++)
    {
        f>>x>>y>>z;
        cap[x][y]+=z;
        edges[x].push_back(y);
        edges[y].push_back(x);
    }
    while(bfs(1, n))
    {
        for(auto y:edges[n])
        {
            tata[n]=y;
            int minflow=INT_MAX;
            for(int x=n; x!=1; x=tata[x])
                minflow=min(minflow, cap[tata[x]][x] - flow[tata[x]][x]);
            for(int x=n; x!=1; x=tata[x])
                flow[tata[x]][x] += minflow, flow[x][tata[x]] -= minflow;
            sflow+=minflow;
        }
    }
    g<<sflow;
    return 0;
}