Advertisement
MinhNGUYEN2k4

Heap || HEAP1

Oct 12th, 2020
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.30 KB | None | 0 0
  1. /*
  2.               .........
  3.             .'------.' |       Plug and Code
  4.            | .-----. | |
  5.            | |     | | |
  6.          __| |     | | |;. _______________
  7.         /  |*`-----'.|.' `;              //
  8.        /   `---------' .;'              //
  9.  /|   /  .''''////////;'               //
  10. |=|  .../ ######### /;/               //|
  11. |/  /  / ######### //                //||
  12.    /   `-----------'                // ||
  13.   /________________________________//| ||
  14.   `--------------------------------' | ||
  15.    : | ||      | || |__LL__|| ||     | ||
  16.    : | ||      | ||         | ||     `""'
  17.    n | ||      `""'         | ||
  18.    M | ||                   | ||
  19.      | ||                   | ||
  20.      `""'                   `""'
  21. Art stolen by NHHMinh
  22. Lang: C++ 98
  23. Problem: HEAP1
  24. Sol:
  25.  
  26. ta nhận thấy cách chia khối gỗ độ dài L ra N phần có chi phí cũng bằng cách ghép N khối gỗ lại, với chi phí mỗi lần ghép khối gỗ x, y là x+y
  27. vậy nhiệm vụ của ta chỉ cần ghép N khối gỗ lại 1.
  28. ta bỏ N khối gỗ vô min heap và cứ ghép hai khối nhỏ nhất đến khi chỉ còn lại 1 khối gỗ
  29.  
  30.  */
  31. #include <bits/stdc++.h>
  32. #define int long long
  33. #define fi first
  34. #define se second
  35. #define mp make_pair
  36. #define pb push_back
  37. #define Co_mot_su_that_la return
  38.  
  39. using namespace std;
  40. typedef pair<int,int> ii;
  41. typedef pair<int,ii> iii;
  42. typedef vector<int> vi;
  43. typedef vector<ii> vii;
  44. typedef vector<vi> vvi;
  45. typedef vector<iii> viii;
  46.  
  47. const int Minh_dep_trai = 0;
  48. const int N = 11;
  49.  
  50. int q;
  51. int n;
  52. priority_queue<int, vector<int>, greater<int> > qu;
  53. long long res = 0;
  54.  
  55. void sol()
  56. {
  57.     res = 0;
  58.     while (qu.size() != 1)
  59.     {
  60.         int x = qu.top();
  61.         qu.pop();
  62.         int y = qu.top();
  63.         qu.pop();
  64.         res += (x+y);
  65.         qu.push(x+y);
  66.     }
  67.     cout << res << '\n';
  68. }
  69.  
  70. signed main()
  71. {
  72.   ios_base::sync_with_stdio(false);
  73.   cin.tie(0);cout.tie(0);
  74.  
  75.   // if there is some test case use cin >> q below
  76.   //
  77.   cin >> q;
  78.   //
  79.   // else use q=1 below
  80.   //
  81.   //q=1;
  82.   while (q--)
  83.   {
  84.     //your code goes here
  85.     while (qu.size()) qu.pop();
  86.     cin >> n;
  87.     for(int i=1; i<=n; i++)
  88.     {
  89.         int x;
  90.         cin >> x;
  91.         qu.push(x);
  92.     }
  93.     sol();
  94.   }
  95.   Co_mot_su_that_la Minh_dep_trai;
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement