Pagini recente » Cod sursa (job #1053788) | Cod sursa (job #3289392) | Cod sursa (job #2528439) | Cod sursa (job #2631528) | Cod sursa (job #2368739)
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
using VI = vector<int>;
using VVI = vector<VI>;
using VB = vector<bool>;
const int Inf = 0x3f3f3f3f;
int n, m;
VB v;
VI t;
VVI G, C;
queue<int> Q;
void Read();
int MaxFlow(int source, int sink);
bool Bfs(int source, int sink);
void Write();
int main()
{
Read();
Write();
}
void Write()
{
ofstream fout("maxflow.out");
fout << MaxFlow(1, n);
fout.close();
}
bool Bfs(int source, int sink)
{
v = VB(n + 1);
Q.push(source);
v[source] = true;
int x;
while (!Q.empty())
{
x = Q.front();
Q.pop();
if (x == sink)
continue;
for (const int& y : G[x])
if (!v[y] && C[x][y] > 0)
{
Q.push(y);
v[y] = true;
t[y] = x;
}
}
return v[sink];
}
int MaxFlow(int source, int sink)
{
int maxflow = 0, flow;
while (Bfs(source, sink))
for (const int& x : G[sink])
{
if (!v[x] || C[x][sink] <= 0)
continue;
flow = Inf;
t[sink] = x;
for (int i = sink; i != source; i = t[i])
flow = min(flow, C[t[i]][i]);
if (!flow)
continue;
for (int i = sink; i != source; i = t[i])
{
C[t[i]][i] -= flow;
C[i][t[i]] += flow;
}
maxflow += flow;
}
return maxflow;
}
void Read()
{
ifstream fin("maxflow.in");
fin >> n >> m;
G = VVI(n + 1);
C = VVI(n + 1, VI(n + 1));
t = VI(n + 1);
int x, y, c;
for (int i = 0; i < m; i++)
{
fin >> x >> y >> c;
G[x].push_back(y);
G[y].push_back(x);
C[x][y] += c;
}
fin.close();
}