fork(1) download
  1. #include <cstdio>
  2. #include <iostream>
  3. #include <cstring>
  4. #include <cmath>
  5. #include <algorithm>
  6. #include <fstream>
  7. #include<stdlib.h>
  8.  
  9. #define rep( i, l, r ) for (int i = l; i <= r; i++)
  10. #define down( i, l, r ) for (int i = l; i >= r; i--)
  11.  
  12. using namespace std;
  13.  
  14. const int DS = 1000000;
  15. const int MaxInt = 1073741823;
  16.  
  17. int ans, n, num[DS], h[DS], l[DS], r[DS];
  18.  
  19. void LRotato(int w)
  20. {
  21. int o = h[w];
  22. if (l[h[o]] == o) l[h[o]] = w; else r[h[o]] = w; h[w] = h[o];
  23. r[o] = l[w]; h[l[w]] = o;
  24. h[o] = w; l[w] = o;
  25. }
  26.  
  27. void RRotato(int w)
  28. {
  29. int o = h[w];
  30. if (l[h[o]] == o) l[h[o]] = w; else r[h[o]] = w; h[w] = h[o];
  31. l[o] = r[w]; h[r[w]] = o;
  32. h[o] = w; r[w] = o;
  33. }
  34.  
  35. void Splay(int w)
  36. {
  37. while (h[w] != 0)
  38. {
  39. if (l[h[w]] == w) RRotato(w); else LRotato(w);
  40. }
  41. }
  42.  
  43. int Pre()
  44. {
  45. int p = l[l[0]];
  46. while (r[p] != 0) p = r[p];
  47. return p;
  48. }
  49.  
  50. int Suf()
  51. {
  52. int p = r[l[0]];
  53. while (l[p] != 0) p = l[p];
  54. return p;
  55. }
  56.  
  57. int Insert(int w)
  58. {
  59. int p = l[0], c = 0;
  60. bool b = false;
  61. while (p != 0)
  62. {
  63. if (num[w] <= num[p])
  64. {
  65. c = p; p = l[p]; b = true;
  66. }
  67. else
  68. {
  69. c = p; p = r[p]; b = false;
  70. }
  71. }
  72. h[w] = c; if (b) l[c] = w; else r[c] = w;
  73. Splay(w);
  74. return min(num[w] - num[Pre()], num[Suf()] - num[w]);
  75. }
  76.  
  77. int main()
  78. {
  79. scanf("%d", &n);
  80. rep(i, 1, n) scanf("%d", &num[i]);
  81. num[n+1] = -MaxInt; num[n+2] = MaxInt; num[0] = 0;
  82. l[0] = n+1; r[n+1] = n+2; h[n+2] = n+1;
  83. ans = Insert(1); ans = num[1];
  84. rep(i, 2, n)
  85. ans += Insert(i);
  86. printf("%d\n", ans);
  87. return 0;
  88. }
  89.  
Success #stdin #stdout 0s 18928KB
stdin
6
5 1 2 5 4 6
stdout
12