SHARE
    TWEET
    Vince14

    Max Flow Sample Code

    Oct 31st, 2023
    144
    0
    Never
    Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
    C++ 1.37 KB | Source Code | 0 0
    1. #include <cstdio>
    2. #include <cstring>
    3. #include <vector>
    4. #include <queue>
    5. #include <algorithm>
    6. #define INF 987654321
    7. using namespace std;
    8. int n, c[52][52], f[52][52];
    9. vector<int> a[52];
    10. int ctoi(char c)
    11. {
    12. if (c >= 'a' && c <= 'z')
    13. return c - 'a';
    14. else
    15. return c - 'A' + 26;
    16. }
    17. // Edmond Karp (BFS)
    18. void network_flow()
    19. {
    20. int total = 0, s = ctoi('A'), t = ctoi('Z');
    21. while (true)
    22. {
    23. int prev[52];
    24. memset(prev, -1, sizeof(prev));
    25. queue<int> q;
    26. q.push(s);
    27. while (!q.empty() && prev[t] == -1)
    28. {
    29. int now = q.front();
    30. q.pop();
    31. for (int next : a[now])
    32. {
    33. if (c[now][next] - f[now][next] > 0 && prev[next] == -1)
    34. {
    35. q.push(next);
    36. prev[next] = now;
    37. if (next == t)
    38. break;
    39. }
    40. }
    41. }
    42. if (prev[t] == -1)
    43. break;
    44. int flow = INF; // 증가경로 중에 최소값
    45. for (int i = t; i != s; i = prev[i])
    46. flow = min(flow, c[prev[i]][i] - f[prev[i]][i]);
    47. for (int i = t; i != s; i = prev[i])
    48. {
    49. f[prev[i]][i] += flow; // 정방향 +
    50. f[i][prev[i]] -= flow; // 역방향 -
    51. }
    52. total += flow;
    53. }
    54. printf("%d\n", total);
    55. }
    56. int main()
    57. {
    58. scanf("%d", &n);
    59. while (n--)
    60. {
    61. char u, v;
    62. int w;
    63. scanf(" %c %c %d", &u, &v, &w);
    64. u = ctoi(u);
    65. v = ctoi(v);
    66. c[u][v] += w;
    67. c[v][u] += w;
    68. a[u].push_back(v);
    69. a[v].push_back(u);
    70. }
    71. network_flow();
    72. return 0;
    73. }
    Advertisement
    Add Comment
    Please, Sign In to add comment
    Public Pastes
    We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
    Not a member of Pastebin yet?
    Sign Up, it unlocks many cool features!

    AltStyle によって変換されたページ (->オリジナル) /