Pagini recente » Cod sursa (job #2066302) | Cod sursa (job #441104) | Clasament gfdgsfdgsd | Cod sursa (job #704043) | Cod sursa (job #3190477)
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#include <cstring>
#include <fstream>
#define MAX_VERTICES 205
using namespace std;
int weights[MAX_VERTICES][MAX_VERTICES], capacities[MAX_VERTICES][MAX_VERTICES], parents[MAX_VERTICES], distances[MAX_VERTICES];
vector<int> graphs[MAX_VERTICES];
bool bellmanFord(int start, int end, int vertices) {
fill(distances, distances + vertices, INT_MAX);
memset(parents, -1, sizeof(parents));
queue<int> q;
distances[start] = 0;
q.push(start);
while (!q.empty()) {
int currentVertex = q.front();
q.pop();
for (int neighbor : graphs[currentVertex]) {
if (capacities[currentVertex][neighbor] > 0 && distances[neighbor] > distances[currentVertex] + weights[currentVertex][neighbor]) {
distances[neighbor] = distances[currentVertex] + weights[currentVertex][neighbor];
parents[neighbor] = currentVertex;
q.push(neighbor);
}
}
}
return distances[end] != INT_MAX;
}
int minCostMaxFlow(int start, int end, int vertices) {
int flow = 0, totalCost = 0;
while (bellmanFord(start, end, vertices)) {
int pathFlow = INT_MAX;
for (int vertex = end; vertex != start; vertex = parents[vertex]) {
int parentVertex = parents[vertex];
pathFlow = min(pathFlow, capacities[parentVertex][vertex]);
}
for (int vertex = end; vertex != start; vertex = parents[vertex]) {
int parentVertex = parents[vertex];
capacities[parentVertex][vertex] -= pathFlow;
capacities[vertex][parentVertex] += pathFlow;
totalCost += pathFlow * weights[parentVertex][vertex];
}
flow += pathFlow;
}
return totalCost;
}
int main() {
ifstream inputFile("cc.in");
ofstream outputFile("cc.out");
int numVertices;
inputFile >> numVertices;
int startVertex = 0, endVertex = 2 * numVertices + 1;
for (int i = 1; i <= numVertices; ++i) {
graphs[startVertex].push_back(i);
capacities[startVertex][i] = 1;
graphs[i + numVertices].push_back(endVertex);
capacities[i + numVertices][endVertex] = 1;
for (int j = 1; j <= numVertices; ++j) {
inputFile >> weights[i][j + numVertices];
weights[j + numVertices][i] = -weights[i][j + numVertices];
graphs[i].push_back(j + numVertices);
graphs[j + numVertices].push_back(i);
capacities[i][j + numVertices] = 1;
}
}
outputFile << minCostMaxFlow(startVertex, endVertex, 2 * numVertices + 2) << endl;
return 0;
}