pku 3264 Balanced Lineup(线段树)

/* Author: ACb0y Date: 2010-9-10 ProblemId: pku 3264 Balanced Lineup Result: AC */ #include <iostream> using namespace std; #define M 50010 #define Max(a, b) (a) > (b) ? (a) : (b) #define Min(a, b) (a) > (b) ? (b) : (a) struct node { int left, right; int min, max; int get_mid() { return (left + right) / 2; } }; int d[M]; node tree[M * 3]; void build(int left, int right, int loc) { int LL = loc << 1; int RR = LL | 1; tree[loc].left = left; tree[loc].right = right; if (left == right) { tree[loc].min = d[left]; tree[loc].max = d[left]; return ; } int mid = tree[loc].get_mid(); build(left, mid, LL); build(mid + 1, right, RR); tree[loc].min = Min(tree[LL].min, tree[RR].min); tree[loc].max = Max(tree[LL].max, tree[RR].max); } int queryMax(int left, int right, int loc) { int LL = loc << 1; int RR = LL | 1; if (tree[loc].left == left && tree[loc].right == right) { return tree[loc].max; } int mid = tree[loc].get_mid(); if (right <= mid) { return queryMax(left, right, LL); } else if (mid < left) { return queryMax(left, right, RR); } else { int a = queryMax(left, mid, LL); int b = queryMax(mid + 1, right, RR); return Max(a, b); } } int queryMin(int left, int right, int loc) { int LL = loc << 1; int RR = LL | 1; if (tree[loc].left == left && tree[loc].right == right) { return tree[loc].min; } int mid = tree[loc].get_mid(); if (right <= mid) { return queryMin(left, right, LL); } else if (mid < left) { return queryMin(left, right, RR); } else { int a = queryMin(left, mid, LL); int b = queryMin(mid + 1, right, RR); return Min(a, b); } } int main() { int n, q; #ifndef ONLINE_JUDGE freopen("3264.txt", "r", stdin); #endif while (cin >> n >> q) { int i, j; for (i = 1; i <= n; i++) { scanf("%d", &d[i]); } build(1, n, 1); for (j = 1; j <= q; j++) { int a, b; scanf("%d%d", &a, &b); printf("%d/n", queryMax(a, b, 1) - queryMin(a, b, 1)); } } return 0; }

你可能感兴趣的:(pku 3264 Balanced Lineup(线段树))