Pagini recente » Cod sursa (job #2987692) | Cod sursa (job #570754) | Cod sursa (job #97563) | Cod sursa (job #484716) | Cod sursa (job #3189497)
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#include <cstring>
#include <fstream>
#define N 205
using namespace std;
int cost[N][N], cap[N][N], par[N], dist[N];
vector<int> g[N];
bool bellmanFord(int s, int t, int n) {
fill(dist, dist + n, INT_MAX);
memset(par, -1, sizeof(par));
queue<int> q;
dist[s] = 0;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : g[u]) {
if (cap[u][v] > 0 && dist[v] > dist[u] + cost[u][v]) {
dist[v] = dist[u] + cost[u][v];
par[v] = u;
q.push(v);
}
}
}
return dist[t] != INT_MAX;
}
int minCostMaxFlow(int s, int t, int n) {
int flow = 0, totalCost = 0;
while (bellmanFord(s, t, n)) {
int path_flow = INT_MAX;
for (int v = t; v != s; v = par[v]) {
int u = par[v];
path_flow = min(path_flow, cap[u][v]);
}
for (int v = t; v != s; v = par[v]) {
int u = par[v];
cap[u][v] -= path_flow;
cap[v][u] += path_flow;
totalCost += path_flow * cost[u][v];
}
flow += path_flow;
}
return totalCost;
}
int main() {
ifstream fin("cc.in");
ofstream fout("cc.out");
int n;
fin >> n;
int s = 0, t = 2 * n + 1;
for (int i = 1; i <= n; ++i) {
g[s].push_back(i);
cap[s][i] = 1;
g[i + n].push_back(t);
cap[i + n][t] = 1;
for (int j = 1; j <= n; ++j) {
fin >> cost[i][j + n];
cost[j + n][i] = -cost[i][j + n];
g[i].push_back(j + n);
g[j + n].push_back(i);
cap[i][j + n] = 1;
}
}
fout << minCostMaxFlow(s, t, 2 * n + 2) << endl;
return 0;
}