Pagini recente » Cod sursa (job #1803500) | Cod sursa (job #3188934) | Cod sursa (job #3282254) | Cod sursa (job #2925617) | Cod sursa (job #3190473)
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#include <cstring>
#include <fstream>
#define MAX_NODES 205
using namespace std;
int weight[MAX_NODES][MAX_NODES], capacity[MAX_NODES][MAX_NODES], parent[MAX_NODES], distance[MAX_NODES];
vector<int> graph[MAX_NODES];
bool bellmanFord(int source, int target, int nodes) {
fill(distance, distance + nodes, INT_MAX);
memset(parent, -1, sizeof(parent));
queue<int> q;
distance[source] = 0;
q.push(source);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : graph[u]) {
if (capacity[u][v] > 0 && distance[v] > distance[u] + weight[u][v]) {
distance[v] = distance[u] + weight[u][v];
parent[v] = u;
q.push(v);
}
}
}
return distance[target] != INT_MAX;
}
int minCostMaxFlow(int source, int target, int nodes) {
int flow = 0, totalCost = 0;
while (bellmanFord(source, target, nodes)) {
int pathFlow = INT_MAX;
for (int v = target; v != source; v = parent[v]) {
int u = parent[v];
pathFlow = min(pathFlow, capacity[u][v]);
}
for (int v = target; v != source; v = parent[v]) {
int u = parent[v];
capacity[u][v] -= pathFlow;
capacity[v][u] += pathFlow;
totalCost += pathFlow * weight[u][v];
}
flow += pathFlow;
}
return totalCost;
}
int main() {
ifstream fin("input.in");
ofstream fout("output.out");
int nodes;
fin >> nodes;
int source = 0, target = 2 * nodes + 1;
for (int i = 1; i <= nodes; ++i) {
graph[source].push_back(i);
capacity[source][i] = 1;
graph[i + nodes].push_back(target);
capacity[i + nodes][target] = 1;
for (int j = 1; j <= nodes; ++j) {