Pagini recente » Cod sursa (job #1622359) | Cod sursa (job #2269149) | Cod sursa (job #581341) | Cod sursa (job #3263418) | Cod sursa (job #1237325)
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
const char infile[] = "maxflow.in";
const char outfile[] = "maxflow.out";
ifstream fin(infile);
ofstream fout(outfile);
const int MAXN = 100005;
const int oo = 0x3f3f3f3f;
typedef vector<int> :: iterator It;
const inline int min(const int &a, const int &b) { if( a > b ) return b; return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b; return a; }
const inline void Get_min(int &a, const int b) { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b) { if( a < b ) a = b; }
class Graph {
private:
unordered_map<int, unordered_map<int, int> > _flow, _capacity;
vector <vector <int> > g;
int N;
vector <bool> used;
vector <int> father;
public:
Graph() {
}
Graph(int N) {
g.resize(N);
used.resize(N);
father.resize(N);
}
void addEdge(int x, int y, int capacity) {
g[x].push_back(y);
g[y].push_back(x);
_capacity[x][y] += capacity;
}
int getMaxFlow(int source, int sink) {
int maxflow = 0;
while(bfs(source, sink)) {
if(father[sink] == -1)
break;
for(It it = g[sink].begin(), fin = g[sink].end(); it != fin ; ++ it) {
if(!used[*it] || _capacity[*it][sink] - _flow[*it][sink] <= 0)
continue;
father[sink] = *it;
int bottleNeck = oo;
for(int i = sink; i != source ; i = father[i])
bottleNeck = min(bottleNeck, _capacity[father[i]][i] - _flow[father[i]][i]);
if(!bottleNeck)
continue;
maxflow += bottleNeck;
for(int i = sink; i != source ; i = father[i]) {
_flow[father[i]][i] += bottleNeck;
_flow[i][father[i]] -= bottleNeck;
}
}
}
return maxflow;
}
bool bfs(int source, int sink) {
fill(used.begin(), used.end(), false);
queue <int> Q;
used[source] = 1;
father[source] = source;
Q.push(source);
while(!Q.empty()) {
int node = Q.front();
Q.pop();
for(It it = g[node].begin(), fin = g[node].end(); it != fin ; ++ it)
if(!used[*it] && _capacity[node][*it] - _flow[node][*it] > 0) {
used[*it] = 1;
father[*it] = node;
Q.push(*it);
}
}
return used[sink];
}
};
int N, M;
int main() {
fin >> N >> M;
Graph G(N);
for(int i = 1 ; i <= M ; ++ i) {
int x, y, c;
fin >> x >> y >> c;
G.addEdge(x - 1, y - 1, c);
}
fout << G.getMaxFlow(0, N - 1) << '\n';
fin.close();
fout.close();
return 0;
}