Pagini recente » Cod sursa (job #1930060) | Cod sursa (job #2737834) | Cod sursa (job #471861) | Cod sursa (job #2745649) | Cod sursa (job #1729817)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <climits>
#include <cstring>
using namespace std;
ifstream fin ("maxflow.in");
ofstream fout ("maxflow.out");
int n,m;
vector<vector<int> > graph;
int cap[1001][1001];
int flow[1001][1001];
vector<bool> vis;
vector<int> T;
bool bfs (int s, int d)
{
fill(vis.begin(), vis.end(), 0);
fill(T.begin(), T.end(), 0);
queue<int> q;
q.push(s);
vis[s] = true;
//vis[d] = false;
T[s] = 0;
//cout<<vis[d]<<" "<<vis[2] <<" "<<d<<endl;
while (!q.empty())
{
int node = q.front();
//cout<<"in bfs "<<q.size()<<" "<<node<<endl;
//if (node == 2)
// exit(1);
q.pop();
if (node == d)
{
// cout<<"da"<<endl;
continue;
}
for (int i = 0; i < graph[node].size(); i++)
{
if (!vis[graph[node][i]] && flow[node][graph[node][i]]
< cap[node][graph[node][i]])
{
vis[graph[node][i]] = true;
T[graph[node][i]] = node;
q.push(graph[node][i]);
}
}
}
// /cout<<(vis[d] == true)<<endl;
return (vis[d] == true);
}
int maxflow (int s, int d)
{
int sol = 0;
while (bfs(s,d)){
//return 1;
vector<int>::iterator it = graph[d].begin();
for (it = graph[d].begin(); it != graph[d].end(); ++it)
{
if (T[*it] != 0 && flow[*it][d] < cap[*it][d])
{
T[d] = *it;
int minflow = INT_MAX;
for (int node = d; node != s; node = T[node])
{
minflow = min (minflow, cap[T[node]][node] - flow[T[node]][node]);
}
sol += minflow;
for (int node = d; node != s; node = T[node]){
flow[T[node]][node] += minflow;
flow[node][T[node]] -= minflow;
}
}
}
}
return sol;
}
int main()
{
fin>>n>>m;
graph.resize(n+1);
vis.resize(n+1);
T.resize(n+1);
for (int i = 1; i <= m;i++)
{
int x,y,z;
fin>>x>>y>>z;
graph[x].push_back(y);
graph[y].push_back(x);
cap[x][y] = z;
}
fout<<maxflow(1,n);
}