Cod sursa(job #2642882)

Utilizator triscacezarTrisca Vicol Cezar triscacezar Data 17 august 2020 14:47:11
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,x,y,z,ANS,cap[1010][1010],fr[1010],dist[1010];
vector<int> v[1010];
priority_queue<pair<int,int> > q;

bool Djikstra(){
	memset(dist,127,sizeof(dist));
	memset(fr,0,sizeof(fr));
	dist[1]=0;
	q.push({0,1});
	while(q.size()){
		int poz=q.top().second,dst=-q.top().first;q.pop();
		if(dst!=dist[poz])continue;
		for(auto it:v[poz])
			if(cap[poz][it])
				if(dist[it]>dist[poz]+1){
					dist[it]=dist[poz]+1;
					q.push({-dist[it],it});
					fr[it]=poz;
				}
	}
	if(dist[n]>n)return 0;
	return 1;
}

void trai(int poz){
	int Min=cap[poz][n],pozz=poz;
	while(pozz!=1){
		Min=min(Min,cap[fr[pozz]][pozz]);
		pozz=fr[pozz];
	}
	if(!Min)return;
	pozz=poz;
	cap[poz][n]-=Min;
	cap[n][poz]+=Min;
	while(pozz!=1){
		cap[pozz][fr[pozz]]+=Min;
		cap[fr[pozz]][pozz]-=Min;
		pozz=fr[pozz];
	}
	ANS+=Min;
	return ;
}

int main(){
	f>>n>>m;
	for(int i=1;i<=m;i++){
		f>>x>>y>>z;
		cap[x][y]=z;
		v[x].push_back(y);
		v[y].push_back(x);
	}
	while(Djikstra()){
		for(auto it:v[n])
			trai(it);
	}
	g<<ANS<<'\n';
}