区间最小值 LightOJ - 1082
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 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).
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.
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
Dataset is huge. Use faster I/O methods.
这题用是求区间最小值 RMQ预处理 或线段树都可以;
RMQ
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int n;
int dp[100010][50];
void rmq()
{
for(int j=1; (1<<j)<=n; j++)
{
for(int i=1; i+(1<<j)-1<=n; i++)
{
dp[i][j]=min(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
}
}
}
int rmq1(int l,int r)
{
int k=(int) log2((double)(r-l+1));
return min(dp[l][k],dp[r-(1<<k)+1][k]);
}
int main()
{
int t,k=1;
scanf("%d",&t);
while(t--)
{
printf("Case %d:\n",k++);
scanf("%d",&n);
int q;
scanf("%d",&q);
for(int j=1; j<=n; j++)
{
scanf("%d",&dp[j][0]);
}
rmq();
while(q--)
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",rmq1(a,b));
}
}
return 0;
}
线段树
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define INF 0x3f3f3f
#define L i<<1,l,mid
#define R i<<1|1,mid+1,r
using namespace std;
int n;
int t[100010<<2];
void creat(int i,int l,int r)
{
if(l==r)
{
scanf("%d",&t[i]);
return ;
}
int mid=(l+r)>>1;
creat(L);creat(R);
t[i]=min(t[i<<1],t[i<<1|1]);
}
int cha(int i,int l,int r,int x,int y)
{
if(x<=l&&r<=y) return t[i];
int mid=(l+r)>>1;
int res=INF;
if(x<=mid) res=min(cha(L,x,y),res);
if(mid<y) res=min(cha(R,x,y),res);
return res;
}
int main()
{
int t,k=1;
scanf("%d",&t);
while(t--)
{
printf("Case %d:\n",k++);
scanf("%d",&n);
int q;
scanf("%d",&q);
creat(1,1,n);
while(q--)
{
int a,b;
scanf("%d%d",&a,&b);
printf("%d\n",cha(1,1,n,a,b));
}
}
return 0;
}