Poj_3264 balanced lineup)

Source: Internet
Author: User

Use a line segment tree for water over 3 s... Don't talk about it. Go to the Code:

#include <stdio.h>
#define inf 0x7fffffff
#define N 50010
struct node
{
int l, r;
int min, max;
}node[N*4];

int num[N], nmax, nmin;
void creat(int t, int l, int r)
{
node[t].l = l;
node[t].r = r;
node[t].min = inf;
node[t].max = -inf;
if(l == r - 1)
{
if(num[l] > num[r])
{
node[t].min = num[r];
node[t].max = num[l];
}
else
{
node[t].min = num[l];
node[t].max = num[r];
}
return;
}
int mid = (l + r) >> 1;
creat(t << 1, l, mid);
creat(t << 1 | 1, mid , r);
node[t].min = node[t << 1].min < node[t << 1 | 1].min ? node[t << 1].min : node[t << 1 | 1].min;
node[t].max = node[t << 1].max > node[t << 1 | 1].max ? node[t << 1].max : node[t << 1 | 1].max;
}
void query(int t, int l, int r)
{
if(node[t].l >= l && node[t].r <= r)
{
nmax = node[t].max > nmax ? node[t].max : nmax;
nmin = node[t].min < nmin ? node[t].min : nmin;
return ;
}
if(node[t].l == node[t].r - 1) return;
int mid = (node[t].l + node[t].r) >> 1;
if(l >= mid)
query(t << 1 | 1, l, r);
else if(r <= mid)
query(t << 1, l, r);
else
{
query(t << 1, l, mid);
query(t << 1 | 1, mid, r);
}
}
int main()
{
int n, q, i;
//freopen("data.in", "r", stdin);
scanf("%d%d", &n, &q);
for(i = 1; i <= n; i++)
scanf("%d", &num[i]);
creat(1, 1, n);
while(q--)
{
int x, y;
scanf("%d%d", &x, &y);
if(x == y)
{
printf("0\n");
continue;
}
nmax = -inf; nmin = inf;
query(1, x, y);
printf("%d\n", nmax - nmin);
}
return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.