Advertisement
sak1b

Untitled

Mar 28th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. using namespace std;
  5.  
  6.  
  7. typedef unsigned int u32;
  8.  
  9. typedef vector<int> IV;
  10.  
  11.  
  12. //
  13. // I/O
  14. //
  15. #define BUF 524288
  16. struct Reader {
  17. char buf[BUF]; char b; int bi, bz;
  18. Reader() { bi=bz=0; read(); }
  19. void read() {
  20. if (bi==bz) { bi=0; bz = fread(buf, 1, BUF, stdin); }
  21. b = bz ? buf[bi++] : 0; }
  22. void skip() { while (b > 0 && b <= 32) read(); }
  23. u32 next_u32() {
  24. u32 v = 0; for (skip(); b > 32; read()) v = v*10 + b-48; return v; }
  25. };
  26.  
  27. //
  28. // Segment Tree
  29. //
  30. struct SegTree {
  31. IV A, M; int n;
  32. SegTree(int N) : n(N) {
  33. A.resize(n); int h = 1 + ceil(log2(n)); M.resize(1 << h); }
  34. void init() { tree_init(1, 0, n - 1); }
  35. int query_val(int i, int j) { return A[tree_query(1, 0, n - 1, i, j)]; }
  36. int query_idx(int i, int j) { return tree_query(1, 0, n - 1, i, j); }
  37. void tree_init(int x, int a, int b) {
  38. if (a == b) { M[x] = a; return; }
  39. int l = 2*x, r = 2*x + 1, m = (a+b)/2;
  40. tree_init(l, a, m);
  41. tree_init(r, m + 1, b);
  42. M[x] = A[M[l]] <= A[M[r]] ? M[l] : M[r];
  43. }
  44. int tree_query(int x, int a, int b, int i, int j) {
  45. if (j < a || i > b) return -1;
  46. if (a >= i && b <= j) return M[x];
  47. int l = 2*x, r = 2*x + 1, m = (a+b)/2;
  48. int q1 = tree_query(l, a, m, i, j);
  49. int q2 = tree_query(r, m + 1, b, i, j);
  50. if (q1 < 0) return q2;
  51. if (q2 < 0) return q1;
  52. return A[q1] <= A[q2] ? q1 : q2;
  53. }
  54. };
  55.  
  56.  
  57. int N;
  58.  
  59.  
  60. int solve(SegTree &t, int i, int j)
  61. {
  62. if (i > j) return 0;
  63. if (i == j) return t.A[i];
  64.  
  65. int midx = t.query_idx(i, j);
  66. int a = (j - i + 1) * t.A[midx];
  67.  
  68. int lt = solve(t, i, midx - 1);
  69. int rt = solve(t, midx + 1, j);
  70.  
  71. if (lt > a) a = lt;
  72. if (rt > a) a = rt;
  73. return a;
  74. }
  75.  
  76. int main()
  77. {
  78. Reader rr;
  79. int T = rr.next_u32();
  80.  
  81. int ncase = 0;
  82. while (T--) {
  83. N = rr.next_u32();
  84.  
  85. SegTree tree(N);
  86. for (int i = 0; i < N; ++i)
  87. tree.A[i] = rr.next_u32();
  88.  
  89. tree.init();
  90.  
  91. printf("Case %d: %d\n", ++ncase, solve(tree, 0, N - 1));
  92. }
  93.  
  94. return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement