NWU_ACM

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

RMQ:

 1 #include <bits/stdc++.h>
 2 #define rep(i,a,b) for(int i = a;i <= b;++ i)
 3 #define per(i,a,b) for(int i = a;i >= b;-- i)
 4 #define mem(a,b) memset((a),(b),sizeof((a)))
 5 #define FIN freopen("in.txt","r",stdin)
 6 #define IO ios_base::sync_with_stdio(0),cin.tie(0)
 7 #define pb push_back
 8 using namespace std;
 9 typedef long long LL;
10 typedef pair<int, int> PIR;
11 const int N = 1e6+5;
12 
13 int n, m, l, r, mm[N], a[N], dp[N][20];
14 
15 void RMQ_init(){
16     rep(i, 1, n)    dp[i][0] = a[i];
17     for(int j = 1; (1<<j) <= n; ++j){
18         for(int i = 0; i+(1<<j)-1 <= n; ++i)
19             dp[i][j] = min(dp[i][j-1], dp[i+(1<<(j-1))][j-1]);
20     }
21 }
22 int RMQ(int l, int r){
23     int k = 0;
24     while(1<<(k+1) <= r-l+1)    k++;
25     return min(dp[l][k], dp[r-(1<<k)+1][k]);
26 }
27 int main()
28 {//IO;
29     //FIN;
30     scanf("%d", &n);
31     rep(i, 1, n)    scanf("%d", &a[i]);
32     RMQ_init();
33     scanf("%d", &m);
34     while(m--){
35         scanf("%d%d", &l, &r);
36         printf("%d\n", RMQ(l, r));
37     }
38     return 0;
39 }
View Code

 线段树:

 1 #include <bits/stdc++.h>
 2 #define rep(i,a,b) for(int i = a;i <= b;++ i)
 3 #define per(i,a,b) for(int i = a;i >= b;-- i)
 4 #define mem(a,b) memset((a),(b),sizeof((a)))
 5 #define FIN freopen("in.txt","r",stdin)
 6 #define IO ios_base::sync_with_stdio(0),cin.tie(0)
 7 #define pb push_back
 8 #define mid ((l+r)>>1)
 9 #define ls (id<<1)
10 #define rs ((id<<1)|1)
11 using namespace std;
12 typedef long long LL;
13 typedef pair<int, int> PIR;
14 const int N = 1e6+5;
15 
16 int n, m, op, x, y, a[N];
17 
18 struct Node{
19     int minn;
20 }node[N*4];
21 void pushUp(int id, int l, int r){
22     node[id].minn = min(node[ls].minn, node[rs].minn);
23 }
24 void build(int id, int l, int r){
25     if(l == r)  { node[id].minn = a[l]; return; }
26     build(ls, l, mid);
27     build(rs, mid+1, r);
28     pushUp(id, l, r);
29 }
30 void update(int id, int l, int r, int p, int val){
31     if(l == r && l == p)    { node[id].minn = val; return; }
32     if(p <= mid)    update(ls, l, mid, p, val);
33     else    update(rs, mid+1, r, p, val);
34     pushUp(id, l, r);
35 }
36 int query(int id, int l, int r, int ql, int qr){
37     if(l == ql && r == qr)  return node[id].minn;
38     if(qr <= mid)   query(ls, l, mid, ql, qr);
39     else if(ql > mid)   query(rs, mid+1, r, ql, qr);
40     else{
41         return min(query(ls, l, mid, ql, mid), query(rs, mid+1, r, mid+1, qr));
42     }
43 }
44 int main()
45 {IO;
46     //FIN;
47     scanf("%d", &n);
48     rep(i, 1, n)    scanf("%d", &a[i]);
49     build(1, 1, n);
50     scanf("%d", &m);
51     while(m--){
52         scanf("%d %d", &x, &y);
53         printf("%d\n", query(1, 1, n, x, y));
54     }
55     return 0;
56 }
View Code

 

posted on 2017-04-25 20:38  NWU_ACM  阅读(103)  评论(0编辑  收藏  举报