Cod sursa(job #3187880)

Utilizator superffffalexandru radu superffff Data 30 decembrie 2023 22:32:32
Problema Flux maxim Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
// Bellman-Ford - O(n*m)
#include <iostream>
#include <fstream>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <cctype>
#include <unordered_map>
#include <cmath>
#include <bitset>
#include <set>
#include <string>
#include <cstring>
#include <algorithm>
#include <deque>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
typedef pair <int,int>iPair;
int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,S,t,x,y,z,ok,nr,C,xc,yc,ans,Min,w,v,weight,u,poz,cost,Max,MOD,val,lvl,MAX,current,st,dr,BASE,mid,semn,T,check,nr0,nrimp,nrpar,block,INF;
int capacity[1005][1005];
vector<int>graf[1005];

int bfs(int s, int t, vector<int>& parent) {
    fill(parent.begin(), parent.end(), -1);
    parent[s] = -2;
    queue<pair<int, int>> q;
    q.push({s, INF});

    while (!q.empty()) {
        int cur = q.front().first;
        int flow = q.front().second;
        q.pop();
        for (int next : graf[cur]) {
            if (parent[next] == -1 && capacity[cur][next]) {
                parent[next] = cur;
                int new_flow = min(flow, capacity[cur][next]);
                if (next == t)
                    return new_flow;
                q.push({next, new_flow});
            }
        }
    }

    return 0;
}

int maxflow(int s, int t) {
    int flow = 0;
    vector<int> parent(n+5);
    int new_flow;

    while (new_flow = bfs(s, t, parent)) {
        flow += new_flow;
        int cur = t;
        while (cur != s) {
            int prev = parent[cur];
            capacity[prev][cur] -= new_flow;
            capacity[cur][prev] += new_flow;
            cur = prev;
        }
    }

    return flow;
}
int main()
{
  in>>n>>m;
  INF=999999999;
  for(i=1;i<=m;i++){
    in>>x>>y>>z;
    graf[x].push_back(y);
    graf[y].push_back(x);
    capacity[x][y]=z;
    capacity[y][x]=0;
  }
  s=1;
  t=n;
  out<<maxflow(s,t);
   return 0;
}