halfo

Isap Flow

Jan 23rd, 2014
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. /* in the name of ALLAH, most gracious, most merciful */
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <limits.h>
  5. #include <algorithm>
  6.  
  7. const int MAX_N = int (1e2) + 7;
  8. const int MAX_E = int (1e4) + 7;
  9.  
  10. int n, e, c;
  11. int src, sink, last [MAX_N], gap [MAX_N], h [MAX_N];
  12. int to [MAX_E], from [MAX_E], flow [MAX_E];
  13.  
  14. inline void add (int u, int v, int c) {
  15.     to [e] = v, from [e] = last [u], last [u] = e, flow [e++] = c;
  16.     to [e] = u, from [e] = last [v], last [v] = e, flow [e++] = c;
  17. }
  18.  
  19. int isap_dfs (int u, int exp) {
  20.     if (u == sink) return exp;
  21.  
  22.     for (int e = last [u]; ~e; e = from [e]) {
  23.         int v = to [e];
  24.         if (flow [e] > 0 && h [v] + 1 == h [u]) {
  25.             int c = isap_dfs (v, std::min (exp, flow [e]));
  26.             flow [e] -= c;
  27.             flow [e ^ 1] += c;
  28.             if (c > 0) return c;
  29.         }
  30.     }
  31.  
  32.     if (--gap [h [u]] == 0) h [src] = n;
  33.     ++gap [++h [u]];
  34.     return 0;
  35. }
  36.  
  37. // nodes are 1 indexed, edges should be added normally for general version
  38. int isap_flow () {
  39.     int ret = 0;
  40.     gap [0] = n;
  41.     while (h [src] < n) ret += isap_dfs (src, INT_MAX);
  42.     return ret;
  43. }
  44.  
  45. void init () {
  46.     e = 0;
  47.     memset (gap, 0, sizeof gap);
  48.     memset (h, 0, sizeof h);
  49.     memset (last, -1, sizeof last);
  50. }
  51.  
  52. int main () {
  53. #ifdef Local
  54.     freopen ("input.txt", "r", stdin);
  55.     // freopen ("output.txt", "w", stdout);
  56. #endif
  57.     int t;
  58.     scanf ("%d", &t);
  59.  
  60.     for (int cs = 1; cs <= t; ++cs) {
  61.         scanf ("%d %d %d %d", &n, &src, &sink, &c);
  62.  
  63.         init ();
  64.         for (int i = 0; i < c; ++i) {
  65.             int u, v, w;
  66.             scanf ("%d %d %d", &u, &v, &w);
  67.             add (u, v, w);
  68.         }
  69.  
  70.         printf ("Case %d: %d\n", cs, isap_flow ());
  71.     }
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment