YauhenMardan

Untitled

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