本文主要是介绍POJ3264(线段树求区间最大值和最小值),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 38054 | Accepted: 17819 | |
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
题目大意:
给定一群羊,再给定一个区间,求区间中最大值 - 最小值是多少,本题如果有朴素暴力做,肯定会超时,就连我用线段树+cin都不能过,要改为scanf。
AC代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;const int INF = 0xfffffff;
const int maxnode = 50001 * 4;int op,qL,qR,p,v; //qL和qR为全局变量,询问区间[qL,qR];struct IntervalTree
{int minv[maxnode];int maxv[maxnode];void update(int o,int L,int R){int M = L + (R - L) / 2;if(L == R){minv[o] = v;maxv[o] = v;}else{if(p <= M) update(o * 2,L,M);elseupdate(o * 2 + 1,M+1,R);minv[o] = min(minv[o * 2],minv[o * 2 + 1]);maxv[o] = max(maxv[o * 2],maxv[o * 2 + 1]);}}int QueryMin(int o,int L,int R){int M = L +(R - L) / 2, ans = INF;if(qL <= L && R <= qR) return minv[o];if(qL <= M) ans = min(ans,QueryMin(o * 2,L,M));if(M < qR) ans = min(ans,QueryMin(o * 2 + 1,M+1,R));return ans;}int QueryMax(int o,int L,int R){int M = L +(R - L) / 2, ans = -INF;if(qL <= L && R <= qR) return maxv[o];if(qL <= M) ans = max(ans,QueryMax(o * 2,L,M));if(M < qR) ans = max(ans,QueryMax(o * 2 + 1,M+1,R));return ans;}
};IntervalTree tree;
int main()
{int m,n;int i;//freopen("111","r",stdin);while(cin>>m>>n){memset(&tree, 0, sizeof(tree));for(i=1;i<=m;i++){p = i;scanf("%d",&v);tree.update(1,1,m);}for(i=1;i<=n;i++){scanf("%d%d",&qL,&qR);printf("%d\n",tree.QueryMax(1,1,m) - tree.QueryMin(1,1,m));}}return 0;
}
这篇关于POJ3264(线段树求区间最大值和最小值)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!