zoukankan      html  css  js  c++  java
  • poj 3264 Balanced Lineup 区间极值RMQ

    题目链接:http://poj.org/problem?id=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.

    题意描述:n个数排成一排形成数组,Q个询问,每个询问给出两个数a和b,求出数组中[a,b]里最大值和最小值的差。

    算法分析:可以用线段树做,在这里介绍RMQ算法。

    RMQ:预处理O(nlogn),然后每次查询O(1)。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<cstdlib>
     5 #include<cmath>
     6 #include<algorithm>
     7 #include<vector>
     8 #define inf 0x7fffffff
     9 using namespace std;
    10 const int maxn=50000+10;
    11 
    12 int n,q;
    13 int an[maxn],dmax[maxn][16],dmin[maxn][16];
    14 
    15 void RMQ_init()
    16 {
    17     for (int i=1 ;i<=n ;i++) dmax[i][0]=dmin[i][0]=an[i];
    18     for (int j=1 ;(1<<j)<=n ;j++)
    19     {
    20         for (int i=1 ;i+(1<<j)-1<=n ;i++)
    21         {
    22             dmax[i][j]=max(dmax[i][j-1],dmax[i+(1<<(j-1))][j-1]);
    23             dmin[i][j]=min(dmin[i][j-1],dmin[i+(1<<(j-1))][j-1]);
    24         }
    25     }
    26 }
    27 
    28 int RMQ(int L,int R)
    29 {
    30     int k=0;
    31     while ((1<<(k+1))<=R-L+1) k++;
    32     int maxnum=max(dmax[L][k],dmax[R-(1<<k)+1][k]);
    33     int minnum=min(dmin[L][k],dmin[R-(1<<k)+1][k]);
    34     return maxnum-minnum;
    35 }
    36 
    37 int main()
    38 {
    39     while (scanf("%d%d",&n,&q)!=EOF)
    40     {
    41         for (int i=1 ;i<=n ;i++) scanf("%d",&an[i]);
    42         RMQ_init();
    43         int a,b;
    44         for (int i=0 ;i<q ;i++)
    45         {
    46             scanf("%d%d",&a,&b);
    47             printf("%d
    ",RMQ(a,b));
    48         }
    49     }
    50     return 0;
    51 }
  • 相关阅读:
    Spring
    linux下jdk多版本管理
    linux集群管理
    python多任务处理
    Web框架的引入
    Git命令大全
    Git远程仓库--GitHub
    基于python实现简单web服务器
    python文件读写方式
    几句话搞懂URI、URL、URN之间的关系
  • 原文地址:https://www.cnblogs.com/huangxf/p/4346067.html
Copyright © 2011-2022 走看看