zoukankan      html  css  js  c++  java
  • poj3264(线段树区间求最值)

    题目连接:http://poj.org/problem?id=3264

    题意:给定Q(1<=Q<=200000)个数A1,A2,```,AQ,多次求任一区间Ai-Aj中最大数和最小数的差。

    线段树功能:区间求最值,O(logN)复杂度查询

    #pragma comment(linker,"/STACK:102400000,102400000")
    #include <cstdio>
    #include <cstring>
    #include <string>
    #include <cmath>
    #include <iostream>
    #include <algorithm>
    #include <queue>
    #include <cstdlib>
    #include <stack>
    #include <vector>
    #include <set>
    #include <map>
    #define LL long long
    #define mod 1000000007
    #define inf 0x3f3f3f3f
    #define N 50010
    #define FILL(a,b) (memset(a,b,sizeof(a)))
    #define lson l,m,rt<<1
    #define rson m+1,r,rt<<1|1
    using namespace std;
    int mx[N<<2],mn[N<<2];
    void Pushup(int rt)
    {
        mn[rt]=min(mn[rt<<1],mn[rt<<1|1]);
        mx[rt]=max(mx[rt<<1],mx[rt<<1|1]);
    }
    void build(int l,int r,int rt)
    {
        if(l==r)
        {
            int x;
            scanf("%d",&x);
            mn[rt]=mx[rt]=x;
            return;
        }
        int m=(l+r)>>1;
        build(lson);
        build(rson);
        Pushup(rt);
    }
    int querymin(int L,int R,int l,int r,int rt)
    {
        if(L<=l&&r<=R)
        {
            return mn[rt];
        }
        int m=(l+r)>>1;
        int res=inf;
        if(L<=m)res=min(res,querymin(L,R,lson));
        if(m<R)res=min(res,querymin(L,R,rson));
        return res;
    }
    int querymax(int L,int R,int l,int r,int rt)
    {
        if(L<=l&&r<=R)
        {
            return mx[rt];
        }
        int m=(l+r)>>1;
        int res=0;
        if(L<=m)res=max(res,querymax(L,R,lson));
        if(m<R)res=max(res,querymax(L,R,rson));
        return res;
    }
    int main()
    {
        int n,m;
        int a,b;
        while(scanf("%d%d",&n,&m)>0)
        {
            build(1,n,1);
            while(m--)
            {
                scanf("%d%d",&a,&b);
                int tallest=querymax(a,b,1,n,1);
                int shortest=querymin(a,b,1,n,1);
                printf("%d
    ",tallest-shortest);
            }
        }
    }
    View Code
  • 相关阅读:
    C#进阶——反射
    C#基础——封装
    Design Patterns——简介
    WEB进阶——this的作用
    C#基础——字段与属性
    ASP.NET MVC基础——添加视图
    ASP.NET MVC基础 ——添加控制器
    C#进阶——var的使用
    C#基础——using的使用
    C#进阶——NPOI
  • 原文地址:https://www.cnblogs.com/lienus/p/4240348.html
Copyright © 2011-2022 走看看