Cod sursa(job #1409959)

Utilizator vladrochianVlad Rochian vladrochian Data 30 martie 2015 19:50:12
Problema Cc Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.36 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

const int kMaxN = 205;

int N, dest, cost;
vector<pair<int, int>> G[kMaxN];
bool cap[kMaxN][kMaxN];

int dist[kMaxN], padre[kMaxN];
queue<int> q;
bool in_q[kMaxN];

void Link(int x, int y, int c) {
	G[x].emplace_back(y, c);
	G[y].emplace_back(x, -c);
	cap[x][y] = true;
}

void Read() {
	ifstream fin("cc.in");
	fin >> N;
	dest = 2 * N + 2;
	for (int i = 0; i < N; ++i) {
		Link(1, i + 2, 0);
		Link(i + N + 2, dest, 0);
		for (int j = 0; j < N; ++j) {
			int c;
			fin >> c;
			Link(i + 2, j + N + 2, c);
		}
	}
}

void BellmanFord() {
	memset(dist, 0x3f, sizeof dist);
	dist[1] = 0;
	q.push(1);
	in_q[1] = true;
	while (!q.empty()) {
		int node = q.front();
		in_q[node] = false;
		q.pop();
		for (auto it : G[node])
			if (cap[node][it.first] && dist[node] + it.second < dist[it.first]) {
				dist[it.first] = dist[node] + it.second;
				padre[it.first] = node;
				if (!in_q[it.first]) {
					q.push(it.first);
					in_q[it.first] = true;
				}
			}
	}
}

void Solve() {
	while (N--) {
		BellmanFord();
		for (int i = dest; i != 1; i = padre[i]) {
			cap[padre[i]][i] = false;
			cap[i][padre[i]] = true;
		}
		cost += dist[dest];
	}
}

int main() {
	Read();
	Solve();
	ofstream("cc.out") << cost << "\n";
	return 0;
}