Pagini recente » Diferente pentru template/algoritmiada-2018/header intre reviziile 7 si 1 | Cod sursa (job #1066973) | Cod sursa (job #3358760) | Cod sursa (job #3357531) | Cod sursa (job #3358004)
#include <fstream>
#include <vector>
#include <queue>
#include <limits>
using namespace std;
const int INF = numeric_limits<int>::max();
struct Muchie {
int destinatie;
int capacitate;
int flux;
int inversa;
};
vector<vector<Muchie>> graf;
vector<int> nivel;
vector<int> tata;
void adaugaMuchie(int sursa, int destinatie, int capacitate) {
Muchie m1 = {destinatie, capacitate, 0, (int)graf[destinatie].size()};
Muchie m2 = {sursa, 0, 0, (int)graf[sursa].size()};
graf[sursa].push_back(m1);
graf[destinatie].push_back(m2);
}
bool BFS(int sursa, int destinatie) {
nivel.assign((int)graf.size(), -1);
nivel[sursa] = 0;
queue<int> coada;
coada.push(sursa);
while (!coada.empty()) {
int nod = coada.front();
coada.pop();
for (const auto& muchie : graf[nod]) {
if (nivel[muchie.destinatie] == -1 && muchie.capacitate > muchie.flux) {
nivel[muchie.destinatie] = nivel[nod] + 1;
coada.push(muchie.destinatie);
}
}
}
return nivel[destinatie] != -1;
}
int DFS(int nod, int destinatie, int flow) {
if (nod == destinatie) {
return flow;
}
for (int i = 0; i < (int)graf[nod].size(); ++i) {
Muchie& muchie = graf[nod][i];
if (nivel[muchie.destinatie] == nivel[nod] + 1 && muchie.capacitate > muchie.flux) {
int flux = DFS(muchie.destinatie, destinatie, min(flow, muchie.capacitate - muchie.flux));
if (flux > 0) {
muchie.flux += flux;
graf[muchie.destinatie][muchie.inversa].flux -= flux;
return flux;
}
}
}
return 0;
}
int EdmondsKarp(int sursa, int destinatie) {
int flux = 0;
while (BFS(sursa, destinatie)) {
int flow = DFS(sursa, destinatie, INF);
while (flow > 0) {
flux += flow;
flow = DFS(sursa, destinatie, INF);
}
}
return flux;
}
int main() {
ifstream f("maxflow.in");
ofstream g("maxflow.out");
int N, M;
f >> N >> M;
graf.resize(N + 1);
nivel.resize(N + 1);
tata.resize(N + 1);
for (int i = 1; i <= M; ++i) {
int x, y, z;
f >> x >> y >> z;
adaugaMuchie(x, y, z);
}
g << EdmondsKarp(1, N);
return 0;
}