Cod sursa(job #1824515)

Utilizator GabiTulbaGabi Tulba-Lecu GabiTulba Data 7 decembrie 2016 22:23:07
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#define MaxN 1005
#define INF 2140000000

using namespace std;

FILE *IN,*OUT;
int N,M,X,Y,C;
int capacity[MaxN][MaxN],flow[MaxN][MaxN],father[MaxN];
bool visited[MaxN];
vector <int> Graph[MaxN];
queue <int> Q;
bool BFS(int Start,int End)
{
	memset(visited,0,sizeof visited);
	memset(father,0,sizeof father);
	visited[Start]=true;
	Q.push(Start);
	while(!Q.empty())
	{
		for(int i=0;i<Graph[Q.front()].size();i++)
			if(!visited[Graph[Q.front()][i]]&&capacity[Q.front()][Graph[Q.front()][i]]-flow[Q.front()][Graph[Q.front()][i]]>0)
			{
				Q.push(Graph[Q.front()][i]);
				father[Graph[Q.front()][i]]=Q.front();
				visited[Graph[Q.front()][i]]=true;
			}
		Q.pop();
	}
	if(father[End])
		return true;
	return false;
}
int Flow(int Source,int Destination)
{
	int F=0,Min;
	while(BFS(Source,Destination))
	{
		Min=INF;
		for(int i=Destination;i!=Source;i=father[i])
			if(capacity[father[i]][i]-flow[father[i]][i]<Min)
				Min=capacity[father[i]][i]-flow[father[i]][i];
		for(int i=Destination;i!=Source;i=father[i])
			flow[father[i]][i]+=Min,flow[i][father[i]]-=Min;
		F+=Min;
	}
	return F;
}
int main()
{
	IN=fopen("maxflow.in","r");
	OUT=fopen("maxflow.out","w");

	fscanf(IN,"%d%d",&N,&M);
	for(int i=1;i<=M;i++)
	{
		fscanf(IN,"%d%d%d",&X,&Y,&C);
		Graph[X].push_back(Y);
		Graph[Y].push_back(X);
		capacity[X][Y]=C;
	}
	fprintf(OUT,"%d",Flow(1,N));
	return 0;
}