poj 3264 Balanced Lineup (线段树模板题)

来源:互联网 发布:只有粤语的电影软件 编辑:程序博客网 时间:2024/05/18 14:23

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 andQ.
Lines 2.. N+1: Line i+1 contains a single integer that is the height of cowi
Lines N+2.. N+ Q+1: Two integers A and B (1 ≤ABN), representing the range of cows from A toB 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 31734251 54 62 2
Sample Output
63

0

直接用线段树求区间最值就可以

ac代码:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int a[2000000],min2,max2;struct node{    int l,r,sum,max1,min1;}tree[2000000];void build(int i,int l,int r){    tree[i].l=l;    tree[i].r=r;    if(l==r)    {        tree[i].min1=tree[i].max1=a[l];        return ;    }    int mid=(l+r)/2;    build(i*2,l,mid);    build(i*2+1,mid+1,r);    tree[i].max1=max(tree[2*i].max1,tree[2*i+1].max1);    tree[i].min1=min(tree[2*i].min1,tree[2*i+1].min1);}void quest(int i,int l,int r){    if(tree[i].max1<=max2&&tree[i].min1>=min2)    return;    if(tree[i].l==l&&tree[i].r==r)    {        min2=min(tree[i].min1,min2);        max2=max(tree[i].max1,max2);        return ;    }    int mid=(tree[i].l+tree[i].r)/2;    if(mid>=r)    quest(i*2,l,r);    else if(mid<l)    quest(i*2+1,l,r);    else    {        quest(i*2,l,mid);        quest(i*2+1,mid+1,r);    }}int main(){    int m,n,x,y;    while(scanf("%d%d",&m,&n)!=-1)    {        for(int i=1;i<=m;i++)        scanf("%d",&a[i]);        build(1,1,m);        for(int i=1;i<=n;i++)        {            scanf("%d%d",&x,&y);            max2=-10000000;            min2=10000000;            quest(1,x,y);            printf("%d\n",max2-min2);        }    }    return 0;}

0 0
原创粉丝点击