• POJ 3264 Balanced Lineup【RMQST算法区间最值】


    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

    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..N+Q+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

    很好的参考资料:http://s99f.blog.163.com/blog/static/3511836520094229354265/
    代码如下:
    View Code
    #include<stdio.h>
    #include<string.h>
    #include<iostream>
    #include<math.h> 
    #include<algorithm>
    using namespace std; 
    #define N 50005 
    int dpmin[N][20], dpmax[N][20]; 
    int main()
    {
        int i, j, n, m;
        scanf("%d%d", &n, &m); 
        memset(dpmin, 0, sizeof(dpmin));
        memset(dpmax, 0, sizeof(dpmax));
        for(i=1; i<=n; i++)
        {
            scanf("%d", &dpmin[i][0]);
            dpmax[i][0]=dpmin[i][0]; 
        }
        int mm=floor(log(1.0*n)/log(2.0));
        for(j=1; j<=mm; j++)
            for(i=n; i>=1; i--)
            {
                if((i+(1<<(j-1)))<=n)
                { 
                    dpmin[i][j]=min(dpmin[i][j-1], dpmin[i+(1<<(j-1))][j-1]);
                    dpmax[i][j]=max(dpmax[i][j-1], dpmax[i+(1<<(j-1))][j-1]);
                } 
            }
        int x, y; 
        for(int i=1; i<=m; i++)
        {
            scanf("%d%d", &x, &y);
            int  mid=floor(log(y*1.0-x+1)/log(2.0));
            int maxnum=max(dpmax[x][mid], dpmax[y-(1<<mid)+1][mid]);
            int minnum=min(dpmin[x][mid], dpmin[y-(1<<mid)+1][mid]);
            printf("%d\n", maxnum-minnum);
        }
    }


  • 相关阅读:
    编程填空:第i位替换
    poj 2192 Zipper
    3:拦截导弹
    vijos 1006 晴天小猪历险记之Hill——数字三角形的终极变化
    数字三角形【汇总】
    codevs 1576 最长严格上升子序列
    3299 有序数组合并求第K大问题
    输出数组第k大的元素
    Java线程同步的Monitor机制(Lock配合Condition)
    堆排序Heapsort的Java和C代码
  • 原文地址:https://www.cnblogs.com/Hilda/p/2633862.html
Copyright © 2020-2023  润新知