码迷,mamicode.com
首页 > 其他好文 > 详细

LightOJ Array Queries 1082【线段树求区间最值】

时间:2015-08-20 22:34:20      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:数据结构   c++   c   c语言   算法   

1082 - Array Queries
Time Limit: 3 second(s) Memory Limit: 64 MB

Given an array with N elements, indexed from 1 to N. Now you will be given some queries in the form I J, your task is to find the minimum value from index I to J.

Input

Input starts with an integer T (≤ 5), denoting the number of test cases.

The first line of a case is a blank line. The next line contains two integers N (1 ≤ N ≤ 105)q (1 ≤ q ≤ 50000). The next line contains N space separated integers forming the array. There integers range in [0, 105].

The next q lines will contain a query which is in the form I J (1 ≤ I ≤ J ≤ N).

Output

For each test case, print the case number in a single line. Then for each query you have to print a line containing the minimum value between index I and J.

Sample Input

Output for Sample Input

2

 

5 3

78 1 22 12 3

1 2

3 5

4 4

 

1 1

10

1 1

Case 1:

1

3

12

Case 2:

10

Note

Dataset is huge. Use faster I/O methods.


解题思路:

线段树,区间最值问题。

AC代码:


#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>

using namespace std;

const int INF = 0x3f3f3f3f;
const int maxn = 200010;

int Max[maxn<<2];

void pushup(int root)
{
    Max[root]=min(Max[root<<1],Max[root<<1|1]);
}

void build(int root,int L,int R)
{
    if(L==R){
        scanf("%d",&Max[root]);
        return;
    }
    int mid=(L+R)>>1;
    build(root<<1,L,mid);
    build(root<<1|1,mid+1,R);
    pushup(root);
}

void update(int root,int L,int R,int i,int v)
{
    if(L==R){
        Max[root]=v;
        return;
    }
    int mid=(L+R)>>1;
    if(i<=mid)update(root<<1,L,mid,i,v);
    else update(root<<1|1,mid+1,R,i,v);
    pushup(root);
}
int query(int root,int L,int R,int s,int e)
{
    if(s==L&&e==R)
    {
        return Max[root];
    }
    int mid=(L+R)>>1;
    int res=INF;
    if(e<=mid) res=min(res,query(root<<1,L,mid,s,e));
    else if(s>mid) res=min(res,query(root<<1|1,mid+1,R,s,e));
    else
    {
        res=min(res,query(root<<1,L,mid,s,mid));
        res=min(res,query(root<<1|1,mid+1,R,mid+1,e));
    }
    return res;
}

int main()
{
    int N,M,a,b;
    int t;
    scanf("%d",&t);
    int xp=0;
    while(t--){
        scanf("%d%d",&N,&M);
        build(1,1,N);
        printf("Case %d:\n",++xp);
        while(M--){
            scanf("%d%d",&a,&b);
            int ans=query(1,1,N,a,b);
            printf("%d\n",ans);
        }
    }
    return 0;
}


版权声明:本文为博主原创文章,转载请注明出处。

LightOJ Array Queries 1082【线段树求区间最值】

标签:数据结构   c++   c   c语言   算法   

原文地址:http://blog.csdn.net/ydd97/article/details/47816331

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!