Description
N (2 <= N <= 8,000) cows have unique brands in the range 1..N. In a spectacular display of poor judgment, they visited the neighborhood 'watering hole' and drank a few too many beers before dinner. When it was time to line up for their evening meal, they did not line up in the required ascending numerical order of their brands.
Regrettably, FJ does not have a way to sort them. Furthermore, he's not very good at observing problems. Instead of writing down each cow's brand, he determined a rather silly statistic: For each cow in line, he knows the number of cows that precede that cow in line that do, in fact, have smaller brands than that cow.
Given this data, tell FJ the exact ordering of the cows.
Input
* Line 1: A single integer, N
* Lines 2..N: These N-1 lines describe the number of cows that precede a given cow in line and have brands smaller than that cow. Of course, no cows precede the first cow in line, so she is not listed. Line 2 of the input describes the number of preceding cows whose brands are smaller than the cow in slot #2; line 3 describes the number of preceding cows whose brands are smaller than the cow in slot #3; and so on.
Output
* Lines 1..N: Each of the N lines of output tells the brand of a cow in line. Line #1 of the output tells the brand of the first cow in line; line 2 tells the brand of the second cow; and so on.
Sample Input
5
1
2
1
0
Sample Output
2
4
5
3
1
这个题目属于线段树问题,可以牛看成个体,进行分解,注意,要求的是一个区间的上的最大值或者最小值的差,所以用一个结构体来记录一个区间的最大值和最小值,尤其注意查找的时候不能改变一个区间上的最大值和最小值,要重新定义一个结构体进行计算;其余的和结构体一样:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdio>
using namespace std;
int cows,gro;
int high[50005];
struct m
{
int maxh;
int minh;
}diff[50005*4];
void build ( int l,int r, int p)
{
if ( l == r ){diff[p].maxh = high[l];diff[p].minh = high[l];return;}
int mid = ( l + r ) / 2;
build(l,mid,2*p);
build(mid+1,r,2*p+1);
diff[p].maxh = max(diff[p*2].maxh, diff[p*2+1].maxh);
diff[p].minh = min(diff[p*2].minh, diff[p*2+1].minh);
}
m finds(int l, int r, int searchl, int searchr,int p)
{
if ( searchl <= l && searchr >= r ) return diff[p];
int mid = ( l + r ) / 2;
if ( searchl > mid ) return finds(mid+1,r,searchl,searchr,2*p+1);
if ( searchr <= mid ) return finds ( l, mid, searchl,searchr,2*p);
m d;
m f,s;
f = finds(mid+1,r,searchl,searchr,2*p+1);
s = finds ( l, mid, searchl,searchr,2*p);///要先计算出来然后再求最小最大值,一起算的话会超时超到哭
d.maxh = max(f.maxh, s.maxh);
d.minh = min(f.minh, s.minh);
return d;///自己定义结构体返回,不能改变原来的最大最小值,因为没有改变数据所以区间上的最大最小值不改变;
}
int main()
{
while ( scanf("%d %d",&cows,&gro)!=EOF )
{
for ( int i = 0; i < cows; i++ )
{
scanf("%d",&high[i]);
}
build(0,cows-1,1);
int fir,sec;
for ( int i = 0; i < gro; i++ )
{
scanf("%d %d",&fir,&sec);
m ans1 = finds(0,cows-1,fir-1,sec-1,1);
int ans = ans1.maxh-ans1.minh;
printf("%d\n",ans);
}
}
}