fork download
  1. #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
  2. #pragma GCC target("avx,avx2,fma")
  3. #include <bits/stdc++.h>
  4. #define f first
  5. #define s second
  6. #define fore(i,a,b) for(int i = (a), ThxMK = (b); i < ThxMK; ++i)
  7. #define pb push_back
  8. #define all(s) begin(s), end(s)
  9. #define rall(s) s.rbegin(), s.rend()
  10. #define _ ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
  11. #define sz(s) int(s.size())
  12. #define ENDL '\n'
  13. using namespace std;
  14. typedef long double ld;
  15. typedef long long lli;
  16. typedef pair<lli,lli> ii;
  17. typedef vector<lli> vi;
  18. #define deb(x) cout << #x": " << (x) << endl;
  19.  
  20. lli c = 0;
  21.  
  22. void awa(deque <lli> &r, lli id){
  23. vi a;
  24. lli l = r[id];
  25. id++;
  26. while (r[id] < l && id < sz(r) - 1){
  27. a.pb(r[id]);
  28. id++;
  29. }
  30. if (id < sz(r)){
  31. lli f = r[id];
  32. if (l > f){
  33. fore (i,0,sz(a)){
  34. c+=(f - a[i]);
  35. }
  36. if (sz(r) - id >= 3){
  37. awa(r, id);
  38. }
  39. else{
  40. return;
  41. }
  42. }
  43. else{
  44. fore (i,0,sz(a)){
  45. c+=(l - a[i]);
  46. }
  47. if (sz(r) - id >= 3){
  48. awa(r, id);
  49. }
  50. else{
  51. return;
  52. }
  53. }
  54. }
  55. else{
  56. lli f = a.back();
  57. a.pop_back();
  58. if (l > f){
  59. fore (i,0,sz(a)){
  60. c+=(f - a[i]);
  61. }
  62. return;
  63. }
  64. else{
  65. fore (i,0,sz(a)){
  66. c+=(l - a[i]);
  67. }
  68. return;
  69. }
  70. }
  71. }
  72.  
  73. int main(){ _
  74. lli x, n;
  75. cin >> x >> n;
  76. deque <lli> r;
  77. fore (i,0,n){
  78. lli a;
  79. cin >> a;
  80. r.pb(a);
  81. }
  82. while (r[0] <= r[1] && sz(r) > 2){
  83. r.pop_front();
  84. n--;
  85. }
  86. while (r[sz(r) - 1] <= r[sz(r) - 2] && sz(r) > 2){
  87. r.pop_back();
  88. n--;
  89. }
  90. if (sz(r) > 3){
  91. awa(r, 0);
  92. }
  93. cout << abs(x - c) << ENDL;
  94. return 0;
  95. }
  96.  
Success #stdin #stdout 0s 4392KB
stdin
20
10
504030201
stdout
20