Pagini recente » Cod sursa (job #2772978) | Cod sursa (job #933912) | Cod sursa (job #1366509) | Cod sursa (job #1670182) | Cod sursa (job #1795604)
#include <fstream>
#include <vector>
#include <queue>
#define INF 1000000
#define MAX_N 100
#define DIM 500
using namespace std;
ifstream f ("cc.in");
ofstream g ("cc.out");
vector <pair <int , int> > edges;
vector <int> G[DIM];
queue <int> q;
int cap[DIM][DIM], cost[DIM][DIM];
int n , m , e , S , D;
int dmin[DIM], father[DIM];
bool inQueue[DIM];
int cnt, totalCost;
void readData() {
f >> n;
m = n;
S = 0; D = n + m + 1;
for(int i = 1; i <= n; ++i) {
G[S].push_back(i);
G[i].push_back(S);
cap[S][i] = 1;
}
for(int i = n + 1; i <= n + m; ++i) {
G[i].push_back(D);
G[D].push_back(i);
cap[i][D] = 1;
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n; ++j) {
int u , v , c;
f >> c;
u = i;
v = j + n;
G[u].push_back(v);
G[v].push_back(u);
cap[u][v] = 1;
cost[u][v] = c;
cost[v][u] = -c;
edges.push_back(make_pair(u, v));
}
}
}
bool bellmanFord() {
for(int i = S; i <= D; ++i) {
inQueue[i] = false;
dmin[i] = INF;
}
int node = S;
q.push(node);
dmin[node] = 0;
while(!q.empty()) {
node = q.front();
q.pop();
inQueue[node] = false;
for(int nxt : G[node])
if(dmin[node] + cost[node][nxt] < dmin[nxt] && cap[node][nxt] > 0) {
father[nxt] = node;
dmin[nxt] = dmin[node] + cost[node][nxt];
if(!inQueue[nxt]) {
inQueue[nxt] = true;
q.push(nxt);
}
}
}
if(dmin[D] == INF) {
return false;
}
else {
cnt++;
node = D;
while(node != S) {
cap[father[node]][node]--;
cap[node][father[node]]++;
totalCost += cost[father[node]][node];
node = father[node];
}
return true;
}
}
int main() {
readData();
while(bellmanFord());
g << totalCost;
return 0;
}