zoukankan      html  css  js  c++  java
  • poj3264RMQ

    Balanced Lineup
    Time Limit: 5000MS   Memory Limit: 65536K
    Total Submissions: 28835   Accepted: 13579
    Case Time Limit: 2000MS

    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 ≤ ABN), 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

    RMQ算法:
     1 #include <iostream>
     2 #include <stdio.h>
     3 #include <queue>
     4 #include <math.h>
     5 #include <string.h>
     6 #include <algorithm>
     7 using namespace std;
     8 #include <vector>
     9 int main()
    10 {
    11     int n,k;
    12     scanf("%d%d",&n,&k);
    13     int dp[20][51000];
    14     memset(dp,0,sizeof(dp));
    15     int dp1[20][51000];
    16     memset(dp1,0,sizeof(dp1));
    17     int i,j;
    18     for(i=1;i<=n;i++)
    19     {
    20         scanf("%d",&dp[0][i]);
    21         dp1[0][i]=dp[0][i];
    22     }
    23     for(i=1;i<=log(n)/log(2);i++)
    24     for(j=1;j<n+(1<<(i-1));j++)
    25     {
    26         dp[i][j]=max(dp[i-1][j],dp[i-1][j+(1<<(i-1))]);
    27         dp1[i][j]=min(dp1[i-1][j],dp1[i-1][j+(1<<(i-1))]);
    28     }
    29     int x,y;
    30     for(i=0;i<k;i++)
    31     {
    32         scanf("%d%d",&x,&y);
    33         int t=log(y-x+1)/log(2);
    34         printf("%d
    ",max(dp[t][x],dp[t][y-(1<<t)+1])-min(dp1[t][x],dp1[t][y+1-(1<<t)]));
    35     }
    36 
    37 }
    View Code
  • 相关阅读:
    迭代
    UIViewController生命周期控制
    JPA相关注解
    正則表達式截取字符串两字符间的内容
    HDU 1789 Doing Homework again
    《从零開始学Swift》学习笔记(Day48)——类型检查与转换
    POJ 3280 Cheapest Palindrome(区间DP)
    JavaScript高级特性之原型
    http协议
    编程算法
  • 原文地址:https://www.cnblogs.com/ERKE/p/3256968.html
Copyright © 2011-2022 走看看