zoukankan      html  css  js  c++  java
  • Balanced Lineup(POJ

    Balanced Lineup(POJ - 3264)

    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

    Line 1: Two space-separated integers, N and Q
    Lines 2.. N+1: Line i+1 contains a single integer that is the height of cow i 
    Lines N+2.. NQ+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

    Output

    Lines 1.. Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.
    Sample Input
    6 3
    1
    7
    3
    4
    2
    5
    1 5
    4 6
    2 2
    Sample Output
    6
    3
    0

    模板题,直接用ST表查询区间的最值相减即可.

    #include<iostream>
    #include<cstring>
    #include<cstdio>
    #include<cmath>
    #include<algorithm>
    using namespace std;
    const int N=50005;
    const int SZ=31;// 
    int maxn[N][SZ],minn[N][SZ],a[N];
    int n,q,i,j;
    int main()
    {
        scanf("%d%d",&n,&q);
        for(i=1;i<=n;i++)
        {
            scanf("%d",&a[i]);
            maxn[i][0]=a[i];//maxn[i][0],即从下标i开始的长度为1的最值 
            minn[i][0]=a[i];
        }
        for(j=1;j<SZ;j++)
        {
            for(i=1;i<=n;i++)
            {
                if(i+(1<<j)-1<=n)
                {
                    maxn[i][j]=max(maxn[i][j-1],maxn[i+(1<<(j-1))][j-1]);//子区间合并 
                    minn[i][j]=min(minn[i][j-1],minn[i+(1<<(j-1))][j-1]);
                }
            }
        }
        while(q--)
        {
            int l,r;
            scanf("%d%d",&l,&r);
            if(l>r)
            swap(l,r);
            int k=log2(r-l+1);
            int MAX=max(maxn[l][k],maxn[r-(1<<k)+1][k]);//此处有maxn[r-(1<<k)+1][k]的原因,因为1<<k不一定等于r-l+1。
                                                        //不加它会造成查询区间不全.但是这样也会造成查询重叠
            int MIN=min(minn[l][k],minn[r-(1<<k)+1][k]);
            printf("%d
    ",MAX-MIN);
        }
    } 
    View Code
    
    
  • 相关阅读:
    Java匹马行天下之一顿操作猛如虎,框架作用知多少?
    ztree树应用
    动态将ASPX生成HTML网页并将网页导出PDF
    实现图片向上不停的无限滚动效果简单代码
    简单的前端正则验证用户输入的数字是否合法
    eclipse出现jdk版本更新导致无法启动
    删除所有视图 删除所有存储过程
    删除所有表的数据
    要求必须全部重复的数据sql--想了半天才写出来的
    查询树节点下的所有子节点包括根节点
  • 原文地址:https://www.cnblogs.com/switch-waht/p/11394073.html
Copyright © 2011-2022 走看看