Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define MAXN 1005
- #define INF 2000000005
- int N, V[MAXN];
- int SegmentTree[4*MAXN];
- #define _Left 2*Index
- #define _Right 2*Index+1
- #define _Middle (Left+Right)/2
- int QueryTree(int A, int B, int Left = 1, int Right = N, int Index = 1) {
- if (A <= Left && Right <= B)
- return SegmentTree[Index];
- int v, idx = 0;
- if (A <= _Middle)
- if (V[(v = QueryTree(A, B, Left, _Middle, _Left))] < V[idx])
- idx = v;
- if (_Middle+1 <= B)
- if (V[(v = QueryTree(A, B, _Middle+1, Right, _Right))] < V[idx])
- idx = v;
- return idx;
- }
- int Ans;
- void ComputeAns(int Left = 1, int Right = N) {
- int idy, idx = QueryTree(Left, Right);
- if (Left <= idx-1) {
- idy = QueryTree(Left, idx-1);
- Ans += (V[idy] - V[idx]);
- ComputeAns(Left, idx-1);
- }
- if (idx+1 <= Right) {
- idy = QueryTree(idx+1, Right);
- Ans += (V[idy] - V[idx]);
- ComputeAns(idx+1, Right);
- }
- }
- std::ifstream In ("xray.in");
- std::ofstream Out("xray.out");
- void BuildTree(int Left = 1, int Right = N, int Index = 1) {
- if (Left == Right) {
- SegmentTree[Index] = Left;
- return;
- } BuildTree(Left, _Middle, _Left), BuildTree(_Middle+1, Right, _Right);
- if (V[SegmentTree[_Left]] <= V[SegmentTree[_Right]])
- SegmentTree[Index] = SegmentTree[_Left];
- else
- SegmentTree[Index] = SegmentTree[_Right];
- }
- void Citire() {
- In >> N;
- V[0] = INF;
- for (int i=1; i<=N; ++i)
- In >> V[i];
- BuildTree();
- }
- int T, Test;
- void Rezolvare() {
- Ans = 0;
- ComputeAns();
- Out << "Case #" << Test << ": " << Ans + V[QueryTree(1, N)] << '\n';
- }
- int main()
- {
- In >> T;
- for (Test=1; Test<=T; ++Test) {
- Citire();
- Rezolvare();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement