Cod sursa(job #1827063)

Utilizator GabiTulbaGabi Tulba-Lecu GabiTulba Data 11 decembrie 2016 13:40:15
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#define MaxN 355
#define INF 2140000000
using namespace std;

FILE *IN,*OUT;


int N,M,S,D,X,Y,Z,C,flow[MaxN][MaxN],cap[MaxN][MaxN],father[MaxN],Dist[MaxN];
vector <pair<int,int>>Graph[MaxN];
bool IQ[MaxN];
queue<int>Q;
bool BF(int start,int end)
{
	int node,son,cost;
	memset(father,0,sizeof father);
	for(int i=1;i<=N;i++)
		Dist[i]=INF;
	Dist[start]=0;
	Q.push(start);
	while(!Q.empty())
	{
		node=Q.front();
		for(int i=0;i<Graph[node].size();i++)
		{
			son=Graph[node][i].first;
			cost=Graph[node][i].second;
			if(Dist[son]>Dist[node]+cost&&cap[node][son]>flow[node][son])
			{
				Dist[son]=Dist[node]+cost,father[son]=node;
				if(!IQ[son])Q.push(son),IQ[son]=true;
			}
		}
		IQ[node]=false;
		Q.pop();
	}
	if(father[end])
		return true;
	else return false;
}
int Flow(int start,int end)
{
	int F=0,Cost=0,Min;
	while(BF(start,end))
	{
		Min=INF;
		for(int i=end;i!=start;i=father[i])
			Min=min(Min,cap[father[i]][i]-flow[father[i]][i]);
		Cost+=Dist[end]*Min;
		for(int i=end;i!=start;i=father[i])
			flow[father[i]][i]+=Min,flow[i][father[i]]-=Min;
	}
	return Cost;
}
int main()
{
	IN=fopen("fmcm.in","r");
	OUT=fopen("fmcm.out","w");

	fscanf(IN,"%d%d%d%d",&N,&M,&S,&D);
	for(int i=1;i<=M;i++)
	{
		fscanf(IN,"%d%d%d%d",&X,&Y,&C,&Z);
		Graph[X].push_back(make_pair(Y,Z));
		Graph[Y].push_back(make_pair(X,-Z));
		cap[X][Y]=C;
	}
	fprintf(OUT,"%d",Flow(S,D));
}