CDOJ-1591(2017 UESTC Training for Graph Theory -A)

A - An easy problem A

Time Limit: 1000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
 

A row number N, Q a query, asking each time over a period of several poor interval is.

Input

The first line of two integers N (1≤N≤50000), Q (1≤Q≤200000). The next line N integers a1 a2 a3 .... an, (1≤ai≤1000000000). Next Q lines of two integers L, R (1≤L≤R≤N).

Output

For each query output line, a poor integer in the interval.

Sample input and output

Sample Input Sample Output
5 3
3 2 7 9 10
1 5
2 3
3 5
8
5
3

Title effect: As stated, interrogation interval maximum value minus minimum

Topic ideas: This title just to maintain the most value range, you can use tree line, block, simple point is RMQ


AC Code:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 5e4+100;
int dpMin[maxn][20],dpMax[maxn][20];
int a[maxn];
int n,q;

void RMQ()
{
    for(int i=1;i<=n;i++)
        dpMin[i][0] = dpMax[i][0] = a[i];

    for (int j=1;j<=log(n)/log(2);j++)
    {
        for(int i=1;i<=n;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 getMin(int l,int r)
{
    int k=log(r-l+1)/log(2.0);
    return min(dpMin[l][k],dpMin[r-(1<<k)+1][k]);
}

int getMax(int l,int r)
{
    int k=log(r-l+1)/log(2.0);
    return max(dpMax[l][k],dpMax[r-(1<<k)+1][k]);
}

int main()
{
    cin>>n>>q;
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    RMQ();
    while(q--)
    {
        int l,r;scanf("%d%d",&l,&r);
        printf("%d\n",getMax(l,r)-getMin(l,r));
    }
    return 0;
}
























Published 110 original articles · won praise 76 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_34731703/article/details/74152715