Cod sursa(job #2387854)

Utilizator mihai50000Mihai-Cristian Popescu mihai50000 Data 25 martie 2019 12:06:46
Problema Flux maxim Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>

using namespace std;

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

const int DIM = 1007;

vector <int> v[DIM];
vector <int> parent;

const int INF = 1e9;

int capacity[DIM][DIM];

bool start[DIM];
bool finish[DIM];

bool bfs(int s, int t)
{
	fill(parent.begin(), parent.end(), 0);
	
	parent[s] = 1;
	
	queue <int> q;
	
	q.push(s);
	
	while(!q.empty())
	{
		int nod = q.front();
		q.pop();
		
		for(int urm : v[nod])
		{
			if(parent[urm] == 0 && capacity[nod][urm])
			{
				parent[urm] = nod;
				q.push(urm);
			}
		}
	}
	
	return (parent[t] != 0);
}

int maxFlow(int s, int t, int n)
{
	int flow = 0;
	
	while(bfs(s, t) == 1)
		for(auto nod : v[n])
		{
			if(capacity[nod][n] == 0 || parent[nod] == 0)
				continue;
			
			parent[n] = nod;
			
	  		int new_flow = 1e9;
				
			for(int i = n; i != s; i = parent[i])
				new_flow = min(new_flow, capacity[parent[i]][i]);
			
			flow += new_flow;
			
			for(int i = n; i != s; i = parent[i])
			{
				capacity[parent[i]][i] -= new_flow;
				capacity[i][parent[i]] += new_flow;
			}
		}
	
	return flow;
}

int main()
{
	int n, m;
	in >> n >> m;
	
	for(int i = 1; i <= m; i++)
	{
		int x, y, c;
		in >> x >> y >> c;
		
		v[x].push_back(y);
		v[y].push_back(x);
		
		capacity[x][y] += c;
	}
	
	parent.resize(n + 2);
	
	out << maxFlow(1, n, n);
}