Pagini recente » Cod sursa (job #2038533) | Cod sursa (job #1858994) | Cod sursa (job #1944744) | Cod sursa (job #1791587) | Cod sursa (job #1553548)
#include<fstream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
vector<int> G[1001];
int N, M, a, b, c, i, T = 0;
int viz[1001];
int from[1001], O[1001], A[1001][1001];
int BFS(int x)
{
queue<int> q;
q.push(x);
viz[x] = T + 1;
int i;
while (q.size())
{
x = q.front();
q.pop();
if (x == N)
{
return 1;
}
for (i = 0; i < G[x].size();++i)
if (viz[G[x][i]] <= T && A[x][G[x][i]]>0)
{
q.push(G[x][i]);
viz[G[x][i]] = T + 1;
from[G[x][i]] = x;
}
}
return 0;
}
void update(int x)
{
for (int i = 0;i < G[x].size();++i)
{
if (A[G[x][i]][N] == 0 || viz[x] != T + 1)
continue;
int leaf = G[x][i];
int duplicate = leaf;
int min_flow = A[G[x][i]][N];
for (;from[leaf];leaf = from[leaf])
min_flow = min(min_flow, A[from[leaf]][leaf]);
leaf = duplicate;
if (A[G[x][i]][N] - min_flow >= 0)
{
A[G[x][i]][N] -= min_flow;
A[N][G[x][i]] += min_flow;
}
else
{
A[G[x][i]][N] += min_flow;
A[N][G[x][i]] -= min_flow;
}
for (;from[leaf];leaf = from[leaf])
{
if (A[from[leaf]][leaf] - min_flow >= 0)
{
A[from[leaf]][leaf] -= min_flow;
A[leaf][from[leaf]] += min_flow;
}
else
{
A[from[leaf]][leaf] += min_flow;
A[leaf][from[leaf]] -= min_flow;
}
}
}
}
void Edmond()
{
while (BFS(1))
{
update(N);
++T;
}
}
int main()
{
in >> N >> M;
for (i = 1; i <= M; ++i)
{
in >> a >> b >> c;
G[a].push_back(b);
A[a][b] = c;
G[b].push_back(a);
}
for (i = 0; i < G[1].size(); ++i)
O[i] = A[1][G[1][i]];
Edmond();
int s = 0;
for (i = 0; i < G[1].size(); ++i)
s += O[i] - A[1][G[1][i]];
out << s;
return 0;
}