Cod sursa(job #580144)

Utilizator pykhNeagoe Alexandru pykh Data 12 aprilie 2011 19:35:10
Problema Cuplaj maxim de cost minim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 2.4 kb
#include<cstdio>
#include<queue>
#include<bitset>
#include<vector>
#include<algorithm>
using namespace std;

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

const int Max_N = 305;
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], edge[Max_N][Max_N];
int dist[Max_N], T[Max_N], ssol[Max_N];
int N, M, D, S, edge_cnt;

int Bellman_Ford()
	{
		while(Q.size())Q.pop();
		in_Q.reset();
		int nod, x;
		memset(T, 0, sizeof(T));
		memset(dist, INF, sizeof(dist));
		
		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 %d %d", &N, &M, &edge_cnt);
		int x, y, cost;
		
		for(int i = 1 ; i <= edge_cnt ; ++i)
		{
			scanf("%d %d %d", &x, &y, &cost);
			++x, y += (N + 1);
			G[x].push_back(y);
			G[y].push_back(x);
			
			C[x][y] = 1;
			
			Cost[x][y] += cost;
			Cost[y][x] -= cost;
			
			edge[x][y] = i;
		}
		
		S = 1;
		D = N + M + 2;
		
		for(int i = 2 ; i <= N + 1 ; ++i)
		{
			G[S].push_back(i);
			G[i].push_back(S);
			Cost[S][i] = Cost[i][S] = 0;
			C[S][i] = 1;
		}
		
		for(int i = N + 2 ; i <= N + M + 1; ++i)
		{
			G[i].push_back(D);
			G[D].push_back(i);
			Cost[i][D] = Cost[D][i] = 0;
			C[i][D] = 1;
		}
			
		
		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];
		}
		int nr = 0;
		for(int i = 2 ; i <= N + 1 ; ++i)
			for(int j = N + 2 ; j < D ; ++j)
				if(C[i][j] && F[i][j])
				{
					ssol[++nr] = edge[i][j];
					break;
				}
		
		printf("%d %d\n", nr, sol);
				
		for(int i =1 ; i <= nr ; ++i)
			printf("%d ", ssol[i]);
		
		return 0;
}