Pagini recente » Cod sursa (job #5741) | Cod sursa (job #1113715) | Cod sursa (job #124678) | Cod sursa (job #2959470) | Cod sursa (job #2810736)
#include <iostream>
#include <fstream>
#include <string.h>
#include <climits>
#include <vector>
#include <queue>
using namespace std;
ifstream in("maxflow.in");
ofstream out("maxflow.out");
const int MAXN = 1001;
int c[MAXN][MAXN], f[MAXN][MAXN], h[MAXN],visited[MAXN];
vector<int> edges[MAXN], edges_reverse[MAXN];
int n,m,source,sink,flow;
bool BFS(vector<int>edges[],vector<int> edges_reverse[] )
{
memset(h,0,sizeof(h));
memset(visited,0,sizeof(visited));
queue<int> Q;
Q.push(sink);
visited[sink]=1;
while(!Q.empty())
{
int x = Q.front();
Q.pop();
for(auto y :edges[x])
{
if(visited[y]==0&&c[x][y]-f[x][y]>0)
{
Q.push(y);
h[y] = x;
visited[y] = 1;
if(y==source)
return true;
}
}
for(auto y : edges_reverse[x])
{
if(visited[y]==0&&f[y][x]>0)
{
Q.push(y);
h[y] = -x;
visited[y] = 1;
if(y==source)
return true;
}
}
}
return false;
}
void maxflow()
{
sink=1;
source=n;
while(BFS(edges,edges_reverse))
{
for(auto node : edges_reverse[source])
if(f[node][source] != c[node][source] && visited[node])
{
h[source] =node;
int fmin=INT_MAX;
for(int nod = source; nod!= sink; nod = h[nod])
fmin=min(fmin, c[h[nod]][nod]-f[h[nod]][nod]);
if (fmin == 0)
continue;
for(int nod = source; nod!=sink; nod = h[nod])
{
f[nod][h[nod]]-=fmin;
f[h[nod]][nod]+=fmin;
}
flow+=fmin;
}
}
}
int main()
{
in>>n>>m;
for(int i=1; i<=m; i++)
{
int x,y,z;
in>>x>>y>>z;
edges[x].push_back(y);
edges_reverse[y].push_back(x);
c[x][y]=z;
f[x][y]=0;
}
maxflow();
out<<flow;
return 0;
}