YauhenMardan

Untitled

Jun 5th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.12 KB | None | 0 0
  1. #include <fstream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. struct Arc {
  7. int b, u, c, f;
  8. size_t back;
  9. };
  10.  
  11. class Graph{
  12. private:
  13. const int INF = 1000*1000*1000;
  14. int n;
  15. int m;
  16. int s;
  17. int t;
  18. int k=INF;
  19.  
  20. int flow;
  21. int cost;
  22.  
  23. vector < vector<Arc> > adjList;
  24.  
  25. vector<int> id;
  26. vector<int> d;
  27. vector<int> q;
  28. vector<int> p;
  29. vector<size_t> p_rib;
  30.  
  31. void add(int a, int b, int u, int c) {
  32. Arc r1 = { b, u, c, 0, adjList[b].size() };
  33. Arc r2 = { a, 0, -c, 0, adjList[a].size() };
  34. adjList[a].push_back (r1);
  35. adjList[b].push_back (r2);
  36. }
  37. public:
  38. Graph(){
  39. flow = 0;
  40. cost = 0;
  41. }
  42. void readGraph(std::ifstream& fin){
  43. fin>>n>>m>>s>>t;
  44. s--;
  45. t--;
  46. adjList.resize(n);
  47. id.resize(n);
  48. d.resize(n);
  49. q.resize(n);
  50. p.resize(n);
  51. p_rib.resize(n);
  52. int a,b,p,c;
  53. for(int i=0;i<m;i++){
  54. fin>>a>>b>>p>>c;
  55. add(a-1, b-1, p, c);
  56. add(b-1, a-1, p, c);
  57. }
  58. }
  59. void count(){
  60. while (flow < k) {
  61. std::fill(id.begin(), id.end(), 0);
  62. std::fill(d.begin(), d.end(), INF);
  63. int qh=0, qt=0;
  64. q[qt++] = s;
  65. d[s] = 0;
  66. while (qh != qt) {
  67. int v = q[qh++];
  68. id[v] = 2;
  69. if (qh == n) qh = 0;
  70. for (size_t i=0; i<adjList[v].size(); ++i) {
  71. Arc & r = adjList[v][i];
  72. if (r.f < r.u && d[v] + r.c < d[r.b]) {
  73. d[r.b] = d[v] + r.c;
  74. if (id[r.b] == 2) {
  75. if (--qh == -1) qh = n-1;
  76. q[qh] = r.b;
  77. }
  78. else if (id[r.b] == 0) {
  79. q[qt++] = r.b;
  80. if (qt == n) qt = 0;
  81. }
  82. id[r.b] = 1;
  83. p[r.b] = v;
  84. p_rib[r.b] = i;
  85. }
  86. }
  87. }
  88. if (d[t] == INF) break;
  89. int addflow = k - flow;
  90. for (int v=t; v!=s; v=p[v]) {
  91. int pv = p[v];
  92. size_t pr = p_rib[v];
  93. addflow = min (addflow, adjList[pv][pr].u - adjList[pv][pr].f);
  94. }
  95. for (int v=t; v!=s; v=p[v]) {
  96. int pv = p[v];
  97. size_t pr = p_rib[v], r = adjList[pv][pr].back;
  98. adjList[pv][pr].f += addflow;
  99. adjList[v][r].f -= addflow;
  100. cost += adjList[pv][pr].c * addflow;
  101. }
  102. flow += addflow;
  103. }
  104. }
  105. int getFlow(){
  106. return flow;
  107. }
  108. int getCost(){
  109. return cost;
  110. }
  111. };
  112.  
  113. int main()
  114. {
  115. std::ifstream fin("input.txt");
  116. std::ofstream fout("output.txt");
  117. Graph gr;
  118. gr.readGraph(fin);
  119. gr.count();
  120. fout<<gr.getFlow()<<"\n"<<gr.getCost()<<"\n";
  121. return 0;
  122. }
Advertisement
Add Comment
Please, Sign In to add comment