Pagini recente » Cod sursa (job #2876453) | Cod sursa (job #2174434) | Cod sursa (job #636855) | Cod sursa (job #2125142) | Cod sursa (job #2750107)
#include <iostream>
#include <fstream>
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#define CODE_START ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#include <vector>
#include <stdio.h>
#include <string.h>
#include <queue>
using namespace std;
const int NMAX = 1010;
const int INF = 1000000000;
int c[NMAX][NMAX];
int flow[NMAX][NMAX];
int currentPathCapacity[NMAX];
int parent[NMAX]; // parcurgere inversa
vector <int> v[NMAX];
int V, E;
int BFS() {
queue <int> q;
q.push(1);
memset(parent, -1, (V + 5) * sizeof(int)); // reinitializam lista parcursa cu -1
parent[1] = -2;
currentPathCapacity[1] = INF;
while (!q.empty()) {
int nod = q.front();
q.pop();
for (auto it : v[nod]) {
if (parent[it] == -1) {
if (c[nod][it] - flow[nod][it] > 0) {
parent[it] = nod;
currentPathCapacity[it] = min(currentPathCapacity[nod], c[nod][it] - flow[nod][it]);
if (it == V)
return currentPathCapacity[it];
q.push(it);
}
}
}
}
return 0; // no more flow to pass :(
}
void updateFlow(int tempFlow) {
int currentNode = V;
while (currentNode != 1) {
int previousNode = parent[currentNode];
flow[previousNode][currentNode] += tempFlow;
flow[currentNode][previousNode] -= tempFlow;
currentNode = previousNode;
}
}
int edmondsKarp() {
int maxFlow = 0;
while (true) {
int tempFlow = BFS();
if (!tempFlow)
break;
maxFlow += tempFlow;
updateFlow(tempFlow);
}
return maxFlow;
}
int main() {
CODE_START;
FILE* fdescriptor = fopen("maxflow.in", "r");
fscanf(fdescriptor, "%d", &V);
fscanf(fdescriptor, "%d", &E);
for (int x, y, cst; E; E--) {
fscanf(fdescriptor, "%d", &x);
fscanf(fdescriptor, "%d", &y);
fscanf(fdescriptor, "%d", &cst);
c[x][y] = cst;
v[x].push_back(y);
v[y].push_back(x);
}
fclose(fdescriptor);
FILE* gdescriptor = fopen("maxflow.out", "w");
fprintf(gdescriptor, "%d", edmondsKarp());
fclose(gdescriptor);
return 0;
}