Advertisement
Guest User

Untitled

a guest
Feb 18th, 2019
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. #define MAXN 1005
  4. #define INF 2000000005
  5.  
  6. int N, V[MAXN];
  7. int SegmentTree[4*MAXN];
  8.  
  9. #define _Left 2*Index
  10. #define _Right 2*Index+1
  11. #define _Middle (Left+Right)/2
  12.  
  13. int QueryTree(int A, int B, int Left = 1, int Right = N, int Index = 1) {
  14. if (A <= Left && Right <= B)
  15. return SegmentTree[Index];
  16.  
  17. int v, idx = 0;
  18. if (A <= _Middle)
  19. if (V[(v = QueryTree(A, B, Left, _Middle, _Left))] < V[idx])
  20. idx = v;
  21. if (_Middle+1 <= B)
  22. if (V[(v = QueryTree(A, B, _Middle+1, Right, _Right))] < V[idx])
  23. idx = v;
  24.  
  25. return idx;
  26. }
  27.  
  28. int Ans;
  29. void ComputeAns(int Left = 1, int Right = N) {
  30. int idy, idx = QueryTree(Left, Right);
  31.  
  32. if (Left <= idx-1) {
  33. idy = QueryTree(Left, idx-1);
  34. Ans += (V[idy] - V[idx]);
  35. ComputeAns(Left, idx-1);
  36. }
  37.  
  38. if (idx+1 <= Right) {
  39. idy = QueryTree(idx+1, Right);
  40. Ans += (V[idy] - V[idx]);
  41. ComputeAns(idx+1, Right);
  42. }
  43. }
  44.  
  45. std::ifstream In ("xray.in");
  46. std::ofstream Out("xray.out");
  47.  
  48. void BuildTree(int Left = 1, int Right = N, int Index = 1) {
  49. if (Left == Right) {
  50. SegmentTree[Index] = Left;
  51. return;
  52. } BuildTree(Left, _Middle, _Left), BuildTree(_Middle+1, Right, _Right);
  53.  
  54. if (V[SegmentTree[_Left]] <= V[SegmentTree[_Right]])
  55. SegmentTree[Index] = SegmentTree[_Left];
  56. else
  57. SegmentTree[Index] = SegmentTree[_Right];
  58. }
  59.  
  60. void Citire() {
  61. In >> N;
  62. V[0] = INF;
  63. for (int i=1; i<=N; ++i)
  64. In >> V[i];
  65.  
  66. BuildTree();
  67. }
  68.  
  69. int T, Test;
  70. void Rezolvare() {
  71. Ans = 0;
  72. ComputeAns();
  73.  
  74. Out << "Case #" << Test << ": " << Ans + V[QueryTree(1, N)] << '\n';
  75. }
  76.  
  77. int main()
  78. {
  79. In >> T;
  80. for (Test=1; Test<=T; ++Test) {
  81. Citire();
  82. Rezolvare();
  83. }
  84.  
  85. return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement