zkw式线段树解决RMQ问题,只需查询,不用更新,很简单,ps: 为什么C++比gcc快那么多啊?gcc提交3047ms,用C++
的话,只需1329ms。
#include <stdio.h> #define DEBUG #ifdef DEBUG #define debug(...) printf( __VA_ARGS__) #else #define debug(...) #endif #define MIN(a, b) (a) < (b) ? (a): (b) #define MAX(a, b) (a) > (b) ? (a): (b) #define inf 20000000 #define N 50001 struct tree_node { int min, max; }; struct tree_node tree[131072]; int cow[N]; int n, M; int min_h, max_h; void build_tree() { int i; for (M = 1; M < (n+2); M <<= 1); //存储数据的叶子节点 for (i = 1; i <= n; i++) { tree[i+M].min = tree[i+M].max = cow[i]; } //不用的叶子节点 for (i = n+1; i%M != 1; i++) { tree[(i%M)+M].min = inf; tree[(i%M)+M].max = -1; } //分支节点 for (i = M-1; i > 0 ; i--) { tree[i].min = MIN(tree[i<<1].min, tree[(i<<1)+1].min); tree[i].max = MAX(tree[i<<1].max, tree[(i<<1)+1].max); } } void query(int s, int t) { max_h = -1; min_h = inf; for (s = s+M-1, t = t+M+1; (s^t) != 1; s >>= 1, t >>= 1) { if (~s&1) { max_h = MAX(max_h, tree[s^1].max); min_h = MIN(min_h, tree[s^1].min); } if (t&1) { max_h = MAX(max_h, tree[t^1].max); min_h = MIN(min_h, tree[t^1].min); } } } int main() { int i, q, s, t; scanf("%d %d", &n, &q); for (i = 1; i <= n; i++) { scanf("%d", cow+i); } build_tree(); while (q--) { scanf("%d %d", &s, &t); query(s, t); printf("%d\n", max_h-min_h); } return 0; }