Pagini recente » Cod sursa (job #419144) | Cod sursa (job #927120) | Cod sursa (job #856275) | Cod sursa (job #2901451) | Cod sursa (job #3186050)
// COMPLEXITATE: O((NlogN)(MN))
#include <iostream>
#include <fstream>
#include <queue>
#include <algorithm>
using namespace std;
ifstream fin("cc.in");
ofstream fout("cc.out");
const int INF = 1e9;
const int N_MAX = 300;
int tata[N_MAX], graf[N_MAX][N_MAX], cost[N_MAX][N_MAX], v[N_MAX], S = 1, D;
struct elem {
int cost, tata, nod;
elem(int _cost, int _nod, int _tata) : nod(_nod), cost(_cost), tata(_tata) {}
};
bool cmp(const elem& x, const elem& y) {
return x.cost > y.cost;
}
// DRUM MINIM SURSA-DESTINATIE
bool dijkstra() {
priority_queue<elem, vector<elem>, decltype(&cmp)> q(cmp);
fill(v, v + N_MAX, INF);
q.push(elem(0, S, -1));
v[S] = 0;
while (!q.empty()) {
elem nod_vf = q.top();
q.pop();
int c = nod_vf.cost;
int nod = nod_vf.nod;
int t = nod_vf.tata;
// IGNORAM
if (c > v[nod])
continue;
tata[nod] = t;
// DESTINATIE?
if (nod == D)
return true;
// ACTUALIZARE
for (int i = 0; i <= D; i++) {
int c_nou = c + cost[nod][i];
if (graf[nod][i] > 0 && c_nou < v[i]) {
v[i] = c_nou;
q.push(elem(c_nou, i, nod));
}
}
}
return false;
}
int main() {
int m;
fin >> m;
D = 2 * m + 2;
// INITIALIZARE
for (int i = 2; i <= m + 1; i++) {
graf[1][i] = graf[i + m][2 * m + 2] = 1;
}
for (int i = 2; i < m + 2; i++) {
for (int j = m + 2; j < 2 * m + 2; j++) {
fin >> cost[i][j];
cost[j][i] = -cost[i][j];
graf[i][j] = 1;
}
}
// FLUX MAXIM (DIJKSTRA)
while (dijkstra()) {
// ACTUALIZARE FLUX
for (int i = D; tata[i] != -1; i = tata[i]) {
--graf[tata[i]][i];
++graf[i][tata[i]];
}
}
// REZ = SUMA COSTURILOR MINIME PT CARE FLUX == 0
int rez = 0;
for (int i = 2; i < m + 2; i++) {
for (int j = m + 2; j < 2 * m + 2; j++) {
if (graf[i][j] == 0) {
rez += cost[i][j];
}
}
}
fout << rez;
return 0;
}