Cod sursa(job #580194)

Utilizator pykhNeagoe Alexandru pykh Data 12 aprilie 2011 20:08:42
Problema Cc Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.08 kb
#include<cstdio>
#include<queue>
#include<bitset>
#include<vector>
#include<algorithm>
using namespace std;

const char in[]="cc.in";
const char out[]="cc.out";

const int Max_N = 350;
const int INF = 0x3f3f3f3f;

queue<int>Q;
bitset<Max_N>in_Q;
vector<int>G[Max_N];

int F[Max_N][Max_N], C[Max_N][Max_N], Cost[Max_N][Max_N];
int dist[Max_N], T[Max_N];
int N, D, S;

int Bellman_Ford()
	{
		while(Q.size())Q.pop();
		in_Q.reset();
		int nod, x;
		//memset(T, 0, sizeof(T));
		//memset(dist, INF, sizeof(dist));
		
		for(int i = 1 ; i<= D ; ++i)
		{
			T[i] = -1;
			dist[i] = INF;
		}
		
		Q.push(S);
		in_Q[S] = true;
		dist[S] = 0;
		while(Q.size())
		{
			nod = Q.front();
			Q.pop();
			in_Q[nod] = false;
			for(unsigned i = 0 ; i < G[nod].size() ; ++i)
			{
				x = G[nod][i];
				if(C[nod][x] - F[nod][x] > 0 && dist[x] > dist[nod] + Cost[nod][x])
				{
					dist[x] = dist[nod] + Cost[nod][x];
					T[x] = nod;
					if(!in_Q[x])
					{
						Q.push(x);
						in_Q[x] = true;
					}
				}
			}
		}
		return (dist[D] != INF) ? dist[D] : 0;
}



int main()
	{
		freopen(in,"r",stdin);
		freopen(out,"w",stdout);
		scanf("%d\n", &N);
		int x, y, cap, cost;
		S = 1;
		D = N + N + 2;
		
		for(int i = 2 ; i <= N + 1 ; ++i)
		{
			G[S].push_back(i);
			G[i].push_back(S);
			C[S][i] = 1;
			
			Cost[i][S] = Cost[S][i] = 0;
			
			for(int j = N + 2 ; j < D ; ++j)
			{
				scanf("%d", &cost);
				G[i].push_back(j);
				G[j].push_back(i);
				
				C[i][j] = 1;
				
				Cost[i][j] = cost;
				Cost[j][i] = -cost;
				
				G[D].push_back(j);
				G[j].push_back(D);
				C[j][D] = 1;
				
				Cost[D][j] = Cost[j][D] = 0;
				
			}
		}
				

		int min_flow = INF;
		int sol = 0;
		
		while(Bellman_Ford())
		{
			min_flow = INF;
			for(int i = D ; i != S ; i = T[i])
				min_flow = min(min_flow, C[T[i]][i] - F[T[i]][i]);
			
			for(int i = D ; i != S ; i = T[i])
			{
				F[T[i]][i] += min_flow;
				F[i][T[i]] -= min_flow;
			}
		sol += min_flow * dist[D];
		}
		
		printf("%d\n", sol);
		
	return 0;
}