Cod sursa(job #404465)

Utilizator BaduBadu Badu Badu Data 26 februarie 2010 10:39:06
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include<fstream>
#include<vector>
#include<queue>
#include<algorithm>

const int maxx = 350;
const int inf = 0x3f3f3f3f;

using namespace std;

vector < pair <short int, short int> > G[maxx];
vector <short int> T(maxx,0);
vector <bool> Viz(maxx,0);
vector <int> dist(maxx,inf);
int C[maxx][maxx];
int F[maxx][maxx];

int n,m,S,D;

inline int min( int a, int b) { return ( a<b?a:b ); }

struct cmp {
	
	bool operator() (const short int &a, const short int &b) const
	{
		
		return dist[a] > dist[b];
	}
};
priority_queue< short, vector< short int > , cmp > Q;

bool Dijkstra(){

	Viz.clear();
	Viz.resize(maxx, false);
	dist.clear();
	dist.resize(maxx,inf);
	
	Q.push(S);
	dist[S]=0;
	Viz[S]=true;
	T[S]=1;
	
	while( !Q.empty() ){
		
		short int nod = Q.top();
		Q.pop();
		Viz[nod] = 0;
		
		vector< pair<short int,short int> >::iterator it;
		for( it = G[nod].begin(); it!=G[nod].end(); it++){
			
			if( C[nod][it->first] <= F[nod][it->first] || dist[it->first] <= dist[nod] + it->second ) continue;
			
			dist[ it->first ] = dist[nod] + it->second;
			T[it->first] = nod;
			
			if(Viz[it->first]) continue;
			
			Viz[it->first]=1;
	
			Q.push(it->first);
		}
	}
	return ( dist[D] < inf );
}
			
	
int main(){
	
	ifstream f("fmcm.in");
	ofstream g("fmcm.out");
	
	f>>n>>m>>S>>D;
	int x,y,c,z;
	while( m-- ) { 
		
		f>>x>>y>>c>>z;
		C[x][y]=c;
		G[x].push_back( make_pair( y,z) );
		G[y].push_back( make_pair( x,-z));
	}
	
	int flow=0,Rez=0;
	
	while( Dijkstra() ){
			short int t;flow=inf;
			for( t=D; t!=S; t=T[t] ) flow = min( flow, C[T[t]][t]-F[T[t]][t] );
			for( t=D; t!=S; t=T[t] ){ F[T[t]][t]+=flow; F[t][T[t]]-=flow; }
			
			Rez += dist[D] * flow;
	}
	
	g<<Rez;
	
return 0;
}