Advertisement
warrior98

ford fulkerson

May 27th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define INF 0x3f3f3f3f
  3. #define NMAX 1005
  4.  
  5. using namespace std;
  6.  
  7. ifstream fin("fisier.in");
  8. ofstream fout("fisier.out");
  9.  
  10. vector<int> G[NMAX];
  11. int C[NMAX][NMAX], p[NMAX];
  12. bool viz[NMAX];
  13.  
  14. bool BFS(int s, int t, int n) {
  15.     int x;
  16.     queue<int> Q;
  17.  
  18.     memset(viz,0,sizeof(viz));
  19.  
  20.     Q.push(s);
  21.     viz[s] = 1;
  22.     p[s] = -1;
  23.  
  24.     while(!Q.empty()) {
  25.         x = Q.front();
  26.         Q.pop();
  27.  
  28.         for(int y=1;y<=n;++y) {
  29.             if(!viz[y] && C[x][y] > 0) {
  30.                 Q.push(y);
  31.                 p[y] = x;
  32.                 viz[y] = 1;
  33.             }
  34.         }
  35.     }
  36.  
  37.     return viz[t];
  38. }
  39.  
  40. int main() {
  41.     int n,m,i,x,y,c,nod;
  42.  
  43.     fin>>n>>m;
  44.     for(i=1;i<=m;++i) {
  45.         fin>>x>>y>>c;
  46.  
  47.         G[x].push_back(y);
  48.         C[x][y] = c;
  49.     }
  50.  
  51.     int flux = 0;
  52.     while(BFS(1, n, n)) {
  53.         int act_flux = INF;
  54.  
  55.         nod = n;
  56.         while(nod != 1) {
  57.             x = p[nod];
  58.             act_flux = min(act_flux, C[x][nod]);
  59.  
  60.             nod = x;
  61.         }
  62.  
  63.         nod = n;
  64.         while(nod != 1) {
  65.             x = p[nod];
  66.  
  67.             C[x][nod] -= act_flux;
  68.             C[nod][x] += act_flux;
  69.  
  70.             nod = x;
  71.         }
  72.  
  73.         flux += act_flux;
  74.     }
  75.  
  76.     fout << flux;
  77.  
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement