Balanced Lineup
Time Limit:5000MS Memory Limit:65536K
Total Submit:35
Accepted:22
Case Time Limit:2000MS
Description
For the daily milking, Farmer John's N
cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John
decides to organize a game of Ultimate Frisbee with some of the cows. To keep
things simple, he will take a contiguous range of cows from the milking lineup
to play the game. However, for all the cows to have fun they should not differ
too much in height.
Farmer John has made a list of Q (1 ≤ Q ≤ 200,000)
potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each
group, he wants your help to determine the difference in height between the
shortest and the tallest cow in the group.
Input
Line 1: Two space-separated integers, N
and Q.
Lines 2..N+1: Line i+1 contains a single integer that is the height
of cow i
Lines N+2..N+Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N),
representing the range of cows from A to B inclusive.
Output
Lines 1..Q: Each line contains a single
integer that is a response to a reply and indicates the difference in height
between the tallest and shortest cow in the range.
Sample Input
6 3
1
7
3
4
2
5
1 5
4 6
2 2
Sample Output
6
3
0
写代码起来超快,看来寒假练的还是有点效果的,但致命的失误也是存在的,比如说写错了答案还是对的,所以自己造的小数据无论怎么样都是
直接跑出来的,这样就得重新检查代码了,也就是写起来快也就没用了。
贴第一次提交写错代码
#include<iostream>
using namespace std;
int n,q;
const int N=200000;
inline int max(int a,int b){return a>b?a:b;}
inline int min(int a,int b){return a<b?a:b;}
inline int mid(int a,int b){return (a+b)>>1;}
struct seg_tree
{
int l,r;
int mi,ma;
};
seg_tree dia[4*N];
int f[N+5];
void maketree(int l,int r,int index)
{
dia[index].l=l;
dia[index].r=r;
if(l==r)
{
dia[index].ma=dia[index].mi=f[l];
return ;
}
int midd=mid(l,r);
maketree(l,midd,index<<1);
maketree(midd+1,r,(index<<1)+1);
dia[index].ma=max(dia[index<<1].ma,dia[(index<<1)+1].ma);
dia[index].mi=min(dia[index<<1].mi,dia[(index<<1)+1].mi);
}
int finds_max(int l,int r,int c)
{
if(dia[c].l==dia[c].r)
return dia[c].ma;
if(dia[c].l==l&&dia[c].r==r)
return dia[c].ma;
int midd=mid(dia[c].l,dia[c].r);
if(r<=midd)
return finds_max(l,r,c*2);
else if(l>midd)
return finds_max(l,r,c*2+1);
else
return max(finds_max(l,midd,c*2),finds_max(l,r,c*2+1));//就是这里悲剧了。在右半部分写错了。应该是finds_max(midd+1,r,c*2+1)
}
int finds_min(int l,int r,int c)
{
if(dia[c].l==dia[c].r)
return dia[c].mi;
if(dia[c].l==l&&dia[c].r==r)
return dia[c].mi;
int midd=mid(dia[c].l,dia[c].r);
if(r<=midd)
return finds_min(l,r,c*2);
else if(l>midd)
return finds_min(l,r,c*2+1);
else
return min(finds_min(l,midd,c*2),finds_min(l,r,c*2+1));//就是这里悲剧了。
}
int main()
{
int i,j;
while(scanf("%d%d",&n,&q)!=EOF)
{
for(i=1;i<=n;i++)
scanf("%d",&f[i]);
maketree(1,n,1);
while(q--)
{
scanf("%d%d",&i,&j);
printf("%d/n",finds_max(i,j,1)-finds_min(i,j,1));
}
}
return 0;
}