Cod sursa(job #2565629)

Utilizator nicolaee2Martinescu Nicolae nicolaee2 Data 2 martie 2020 15:35:37
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include<bits/stdc++.h>
#include<string.h>

using namespace std;

#define NMAX 1005
#define INF (1<<30)-1

ifstream fin("cod1.in");
ofstream fout("cod1.out");

int n,m,s;
vector<int> ma[NMAX];
int cap[NMAX][NMAX];

void citire()
{
   fin>>n>>m;
   for(int i=1;i<=m;i++)
   {
      int x,y,c;
      fin>>x>>y>>c;
      cap[x][y] += c;
      cap[y][x] = 0;
      ma[x].push_back(y);
      ma[y].push_back(x);
   }

}


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 i=0;i<ma[cur].size();i++)
         {
            int next = ma[cur][i];
            if (parent[next] == -1 && cap[cur][next]) {
                parent[next] = cur;
                int new_flow = min(flow, cap[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+1);
    int new_flow;

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

    return flow;
}

int main()
{

   citire();
   fout<<maxflow(1,n);

}