poj3264 线段树
Posted 当蜗牛有了理想
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj3264 线段树相关的知识,希望对你有一定的参考价值。
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 44121 | Accepted: 20715 | |
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
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
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
好久没写,写搓了,orz
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=70000;
int a[maxn];
int x,y;
struct nod
{
int mi;
int ma;
};
nod tree[4*maxn];
void build(int p,int l,int r)
{
if(l==r) {tree[p].mi=a[l];tree[p].ma=a[l];return;}
int mid=(l+r)>>1;
build(p<<1,l,mid);
build((p<<1)+1,mid+1,r);
tree[p].mi=min(tree[p<<1].mi,tree[(p<<1)+1].mi);
tree[p].ma=max(tree[p<<1].ma,tree[(p<<1)+1].ma);
}
int find1(int p,int l,int r,int x,int y)
{
if(x<=l&&r<=y) {return tree[p].ma;}
int mid=(l+r)>>1;
if(y<=mid) return find1(p<<1,l,mid,x,y);
else if(x>mid) return find1((p<<1)+1,mid+1,r,x,y);
else return max(find1(p<<1,l,mid,x,mid),find1((p<<1)+1,mid+1,r,mid+1,y));
}
int find2(int p,int l,int r,int x,int y)
{
if(x<=l&&r<=y) {return tree[p].mi;}
int mid=(l+r)>>1;
if(y<=mid) return find2(p<<1,l,mid,x,y);
else if(x>mid) return find2((p<<1)+1,mid+1,r,x,y);
else return min(find2(p<<1,l,mid,x,mid),find2((p<<1)+1,mid+1,r,mid+1,y));
}
int main()
{
int n,q;
int x,y;
while(scanf("%d%d",&n,&q)!=EOF)
{
memset(tree,0,sizeof(tree));
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
build(1,1,n);
while(q--)
{
scanf("%d%d",&x,&y);
printf("%d\n",find1(1,1,n,x,y)-find2(1,1,n,x,y));
}
}
return 0;
}
以上是关于poj3264 线段树的主要内容,如果未能解决你的问题,请参考以下文章