Time Limit: 3 second(s) | Memory Limit: 64 MB |
Given an array with N elements, indexed from 1to N. Now you will be given some queries in the form I J, yourtask 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 linecontains two integers N (1 ≤ N ≤ 105), q (1≤ q ≤ 50000). The next line contains N space separatedintegers forming the array. There integers range in [0, 105].
The next q lines will contain a query which is in theform 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 valuebetween 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
|
水题
ac代码:
#include<stdio.h>
#define MAXN 100100
int MIN(int a,int b)
{
return a>b?b:a;
}
struct s
{
int left;
int right;
int min;
}tree[MAXN*3];
int num[MAXN];
void build(int l,int r,int i)
{
tree[i].left=l;
tree[i].right=r;
if(l==r)
{
tree[i].min=num[l];
}
else
{
int mid;
mid=(l+r)/2;
build(l,mid,i*2);
build(mid+1,r,i*2+1);
tree[i].min=MIN(tree[i*2].min,tree[i*2+1].min);
}
}
int query(int i,int l,int r)
{
if(tree[i].left==l&&tree[i].right==r)
{
return tree[i].min;
}
if(r<=tree[i*2].right)
{
return query(i*2,l,r);
}
if(l>=tree[i*2+1].left)
{
return query(i*2+1,l,r);
}
int mid=(tree[i].left+tree[i].right)/2;
return MIN(query(i*2,l,mid),query(i*2+1,mid+1,r));
}
int main()
{
int n,m,t;
int i,a,b;
int cas=0;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++)
scanf("%d",&num[i]);
build(1,n,1);
printf("Case %d:\n",++cas);
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
printf("%d\n",query(1,a,b));
}
}
return 0;
}