Balanced Lineup(线段树的简单了解)
个人心得:线段树就是将一段序列拆分为一个个单独的节点,不过每俩个节点又可以联系在一起,所以就能很好的结合,比如这一题,
每次插入的时候都将这一段区间的最大最小值更新,就能大大减少时间。
这个线段树建立是以数组的,根节点为0,后面每次都是父节点*2+1/2。
这题简单的教会了我如何创建线段树,以及一些简单的线段树操作,还要继续加深。
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
#include <stdio.h>
#include <string.h>
#include<iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int inf=0xffffff0;
int maxa=-inf;
int mina=inf;
struct tree
{
int l,r;
int maxt,mint;
int mid()
{
return (l+r)/;
} };
tree Tree[];
void builttree(int root,int x,int y){
Tree[root].l=x;
Tree[root].r=y;
Tree[root].maxt=-inf;
Tree[root].mint=inf;
if(x!=y){
builttree(root*+,x,(x+y)/);
builttree(root*+,(x+y)/+,y);
}
}
void inserttree(int root,int i,int v){
if(Tree[root].l==i&Tree[root].r==i)
{
Tree[root].maxt=Tree[root].mint=v;
return;
}
Tree[root].maxt=max(Tree[root].maxt,v);
Tree[root].mint=min(Tree[root].mint,v);
if(i<=Tree[root].mid())
inserttree(root*+,i,v);
else
inserttree(root*+,i,v); }
void checktree(int root,int x,int y){
if(Tree[root].maxt<=maxa&&Tree[root].mint>=mina)
return;
if(Tree[root].l==x&&Tree[root].r==y)
{
maxa=max(maxa,Tree[root].maxt);
mina=min(mina,Tree[root].mint);
return ;
}
if(y<=Tree[root].mid())
checktree(root*+,x,y);
else if(x>Tree[root].mid())
checktree(root*+,x,y);
else {
checktree(root*+,x,Tree[root].mid());
checktree(root*+,Tree[root].mid()+,y);
} }
int main()
{
int n,m;
scanf("%d%d",&n,&m);
builttree(,,n);
for(int i=;i<=n;i++)
{
int x;
scanf("%d",&x);
inserttree(,i,x);
}
for(int i=;i<=m;i++)
{
int x,y;
scanf("%d%d",&x,&y);
mina=inf,maxa=-inf;
checktree(,x,y);
printf("%d\n",maxa-mina);
} return ; }
最新文章
- 11、ASP.NET MVC入门到精通——AspnetMVC分页
- 安装和使用cocoapods
- JS-流程控制汇集
- yum简单安装salt master与minion
- CDN技术分享
- velocity序列动画
- WDCP控制面板的常用liunx命令集
- 解决set /p yn= 接受键盘输入导致ECHO 处于关闭状态的问题
- 强制改变IE中的文本模式
- jquery $提示缺少对象$提示缺少对象
- JavaWeb开发技术基础概念回顾篇
- python全栈开发-Day5 元组、字典
- System startup files
- Java_循环
- 用jquery制作简易日历
- Oracle 服务器结构
- E - Radar Installation
- Sql 嵌套循环
- gridview空间使用
- 008-centos服务管理