Pagini recente » Cod sursa (job #1042339) | Cod sursa (job #3002094) | Cod sursa (job #2805110) | Cod sursa (job #675376) | Cod sursa (job #2051086)
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int N_MAX = 1010;
const int CAP_MAX = 110010;
vector < int > g[N_MAX];
int cap[N_MAX][N_MAX];
int flow[N_MAX][N_MAX];
int dad[N_MAX];
bool sour[N_MAX];
bool dest[N_MAX];
int main()
{
freopen("maxflow.in", "r", stdin);
freopen("maxflow.out", "w", stdout);
int n, m;
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i++)
{
int x, y, c;
scanf("%d%d%d", &x, &y, &c);
sour[y] = true;
dest[x] = true;
g[x].push_back(y);
g[y].push_back(x);
cap[x][y] = c;
}
int source;
for(int i = 1; i <= n; i++)
if(sour[i] == false)
{
source = i;
break;
}
int destination;
for(int i = 1; i <= n; i++)
if(dest[i] == false)
{
destination = i;
for(int j = 0; j < g[i].size(); j++)
dest[g[i][j]] = false;
break;
}
bool ok = true;
while(ok == true)
{
ok = false;
queue < pair< int, int > > q;
q.push({source, CAP_MAX});
memset(dad, 0, sizeof(dad));
while(!q.empty())
{
pair < int, int > node = q.front();
q.pop();
for(int i = 0; i < g[node.first].size(); i++)
{
int next = g[node.first][i];
if(dad[next] == 0 && cap[node.first][next] - flow[node.first][next] > 0)
{
dad[next] = node.first;
int mini = min(node.second, cap[node.first][next] - flow[node.first][next]);
q.push({next, mini});
if(dest[next] == false && cap[next][destination] - flow[next][destination] > 0)
{
ok = true;
mini = min(mini, cap[next][destination] - flow[next][destination]);
dad[destination] = next;
for(int i = destination; i != source; i = dad[i])
{
flow[dad[i]][i] += mini;
flow[i][dad[i]] -= mini;
}
}
}
}
}
}
long long flowmax = 0;
for(int i = 0; i < g[source].size(); i++)
flowmax += flow[source][g[source][i]];
printf("%lld\n", flowmax);
return 0;
}