Pagini recente » Cod sursa (job #1619959) | Istoria paginii runda/winners22/clasament | Cod sursa (job #949187) | Cod sursa (job #1510953) | Cod sursa (job #875152)
Cod sursa(job #875152)
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
typedef vector<int>::iterator it;
const int MaxN = 1005;
const int MaxE = 5005;
const int oo = 1000000000;
const int NIL = -1;
struct Edge {
int V, Capacity, Flow;
};
vector<int> G[MaxN];
Edge E[MaxE];
int N, M, Source, Sink, Father[MaxN], MaxFlow;
queue<int> Q;
inline int NonE(const int e) {
return e < M ? e + M : e - M;
}
inline void InitBFS(const int Start) {
memset(Father, NIL, sizeof(Father));
Q.push(Start), Father[Start] = Start;
}
bool BFS(const int Start, const int End) {
for (InitBFS(Start); !Q.empty(); Q.pop()) {
int X = Q.front();
if (X == End)
continue;
for (it e = G[X].begin(); e != G[X].end(); ++e)
if (Father[E[*e].V] == NIL && E[*e].Capacity > E[*e].Flow)
Q.push(E[*e].V), Father[E[*e].V] = NonE(*e);
}
return (Father[End] != NIL);
}
void MaximumFlow() {
while (BFS(Source, Sink)) {
for (it e = G[Sink].begin(); e != G[Sink].end(); ++e) {
if (Father[E[*e].V] == NIL || E[NonE(*e)].Capacity <= E[NonE(*e)].Flow)
continue;
Father[Sink] = *e;
int Flow = oo;
for (int X = Sink; X != Source; X = E[Father[X]].V)
Flow = min(Flow, E[NonE(Father[X])].Capacity-E[NonE(Father[X])].Flow);
for (int X = Sink; X != Source; X = E[Father[X]].V)
E[NonE(Father[X])].Flow += Flow, E[Father[X]].Flow -= Flow;
MaxFlow += Flow;
}
}
}
void Read() {
ifstream fin("maxflow.in");
fin >> N >> M;
for (int i = 0; i < M; ++i) {
int X, Y, C; fin >> X >> Y >> C;
G[X].push_back(i), G[Y].push_back(i+M);
E[i].V = Y, E[i].Capacity = C, E[i].Flow = 0;
E[NonE(i)].V = X, E[NonE(i)].Capacity = 0, E[NonE(i)].Flow = 0;
}
Source = 1, Sink = N;
fin.close();
}
void Print() {
ofstream fout("maxflow.out");
fout << MaxFlow << "\n";
fout.close();
}
int main() {
Read();
MaximumFlow();
Print();
return 0;
}