Advertisement
trungore10

Untitled

Dec 23rd, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. /// complexity : m^2 * n
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. const int N = 1004, oo = 1e9+7;
  6. int n, m, S, T, c[N][N];
  7. vector<int> adj[N];
  8.  
  9. queue<int> Q;
  10. int tr[N];
  11. bool vis[N];
  12.  
  13. bool BFS() {
  14. for (int i = 1; i <= n; ++i) vis[i] = false, tr[i] = 0;
  15. while (Q.size()) Q.pop();
  16. vis[S] = true; Q.push(S);
  17. while (Q.size()) {
  18. int u = Q.front(); Q.pop();
  19. if (u == T) return true;
  20. for (int v : adj[u]) {
  21. if (c[u][v] <= 0 || vis[v]) continue;
  22. tr[v] = u; vis[v] = true; Q.push(v);
  23. }
  24. }
  25. return false;
  26. }
  27.  
  28. vector<int> Path;
  29. int res = 0;
  30.  
  31. void FixGraph() {
  32. int v = T; Path.clear();
  33. while (v != S) { Path.push_back(v); v = tr[v]; } Path.push_back(S);
  34. reverse(Path.begin(), Path.end());
  35. int minCost = oo;
  36. for (int i = 0; i < Path.size()-1; ++i) minCost = min(minCost, c[Path[i]][Path[i+1]]);
  37. for (int i = 0; i < Path.size()-1; ++i) {
  38. int u = Path[i], v = Path[i+1];
  39. c[u][v] -= minCost; c[v][u] += minCost;
  40. }
  41. res += minCost;
  42. }
  43.  
  44. void sol() {
  45. while (true) {
  46. if (!BFS()) break;
  47. FixGraph();
  48. }
  49. cout << res;
  50. }
  51.  
  52. int main() {
  53. ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  54.  
  55. cin >> n >> m >> S >> T;
  56. int u, v, w;
  57. for (int i = 1; i <= m; ++i) {
  58. cin >> u >> v >> w;
  59. adj[u].push_back(v); adj[v].push_back(u);
  60. c[u][v] = w;
  61. }
  62.  
  63. sol();
  64.  
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement