Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<vector>
- #include<queue>
- #include<cstring>
- #include<fstream>
- using namespace std;
- const int MAX_N = 1024;
- const int inf = 989654321;
- int n, m;
- int s, t;
- int u, v, c;
- int ans;
- struct edg
- {
- int to, c, r;
- };
- vector<edg> sys[MAX_N];
- int level[MAX_N];
- int firstE[MAX_N];
- int dfs(int curr, int capacity)
- {
- if(curr == t){
- return capacity;
- }
- int leftcapacity = capacity;
- for(int i = firstE[curr]; i < sys[curr].size(); i++){
- if(level[sys[curr][i].to] > level[curr] && sys[curr][i].c > 0){
- int res = dfs(sys[curr][i].to, min(leftcapacity, sys[curr][i].c));
- if(res == 0){
- firstE[curr] = i+1;
- }else{
- sys[curr][i].c -= res;
- sys[sys[curr][i].to][sys[curr][i].r].c += res;
- leftcapacity -= res;
- }
- }
- if(leftcapacity == 0){break;}
- }
- return capacity - leftcapacity;
- }
- int bfs()
- {
- queue<int> q;
- q.push(s);
- int curr;
- memset(level, -1, sizeof(level));
- level[s] = 0;
- while(!q.empty()){
- curr = q.front();
- q.pop();
- if(curr == t){break;}
- for(int i = 0; i < sys[curr].size(); i++){
- if(level[sys[curr][i].to] == -1 && sys[curr][i].c > 0){
- level[sys[curr][i].to] = level[curr]+1;
- q.push(sys[curr][i].to);
- }
- }
- }
- memset(firstE, 0, sizeof(firstE));
- int res = dfs(s, inf);
- return res;
- }
- int main(){
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- /*#define cin myFileIn
- ifstream myFileIn;
- myFileIn.open("maxflow.in");
- #define cout myFileOut
- ofstream myFileOut;
- myFileOut.open("maxflow.out");*/
- cin >> n >> m;
- s = 0;
- t = n-1;
- for(int i = 0; i < m; i++){
- cin >> u >> v >> c;
- u--;
- v--;
- sys[u].push_back({v, c, sys[v].size()});
- sys[v].push_back({u, 0, sys[u].size()-1});
- }
- int add = bfs();
- while(add > 0){
- ans += add;
- add = bfs();
- }
- cout << ans << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement