USACO Section 4.2: Drainage Ditches

最大流的模板题

 1 /*

 2 ID: yingzho1

 3 LANG: C++

 4 TASK: ditch

 5 */

 6 #include <iostream>

 7 #include <fstream>

 8 #include <string>

 9 #include <map>

10 #include <vector>

11 #include <set>

12 #include <algorithm>

13 #include <stdio.h>

14 #include <queue>

15 #include <cstring>

16 #include <cmath>

17 #include <list>

18 #include <cstdio>

19 #include <cstdlib>

20 #include <limits>

21 #include <stack>

22 

23 using namespace std;

24 

25 ifstream fin("ditch.in");

26 ofstream fout("ditch.out");

27 

28 const int MAX = 210;

29 const int INF = 2000000000;

30 

31 int N, M;

32 int g[MAX][MAX], f[MAX][MAX], pre[MAX], inc[MAX];

33 

34 bool bfs(int s, int d) {

35     queue<int> que;

36     for (int i = 1; i <= M; i++) pre[i] = -1;

37     que.push(s);

38     inc[s] = INF;

39     while (!que.empty()) {

40         int u = que.front();

41         que.pop();

42         for (int i = 1; i <= M; i++) {

43             if (pre[i] == -1 && f[u][i] < g[u][i]) {

44                 inc[i] = min(inc[u], g[u][i]-f[u][i]);

45                 pre[i] = u;

46                 if (i == d) return true;

47                 que.push(i);

48             }

49         }

50     }

51     return false;

52 }

53 

54 int edmond_karp(int s, int d) {

55     int maxflow = 0;

56     while (bfs(s, d)) {

57         maxflow += inc[d];

58         for (int i = d; i != s; i = pre[i]) {

59             f[pre[i]][i] += inc[d];

60             f[i][pre[i]] -= inc[d];

61         }

62     }

63     return maxflow;

64 }

65 

66 int main()

67 {

68     fin >> N >> M;

69     int s, d, e;

70     for (int i = 0; i < N; i++) {

71         fin >> s >> d >> e;

72         g[s][d] += e;

73     }

74     fout << edmond_karp(1, M) << endl;

75 

76     return 0;

77 }

 

你可能感兴趣的:(USACO)