zoukankan      html  css  js  c++  java
  • POJ_3264 Balanced Lineup(线段树练手题)

      用线段树水过,3s多。。。不说了,上代码:

    #include <stdio.h>
    #define inf 0x7fffffff
    #define N 50010
    struct node
    {
    int l, r;
    int min, max;
    }node[N
    *4];

    int num[N], nmax, nmin;
    void creat(int t, int l, int r)
    {
    node[t].l
    = l;
    node[t].r
    = r;
    node[t].min
    = inf;
    node[t].max
    = -inf;
    if(l == r - 1)
    {
    if(num[l] > num[r])
    {
    node[t].min
    = num[r];
    node[t].max
    = num[l];
    }
    else
    {
    node[t].min
    = num[l];
    node[t].max
    = num[r];
    }
    return;
    }
    int mid = (l + r) >> 1;
    creat(t
    << 1, l, mid);
    creat(t
    << 1 | 1, mid , r);
    node[t].min
    = node[t << 1].min < node[t << 1 | 1].min ? node[t << 1].min : node[t << 1 | 1].min;
    node[t].max
    = node[t << 1].max > node[t << 1 | 1].max ? node[t << 1].max : node[t << 1 | 1].max;
    }
    void query(int t, int l, int r)
    {
    if(node[t].l >= l && node[t].r <= r)
    {
    nmax
    = node[t].max > nmax ? node[t].max : nmax;
    nmin
    = node[t].min < nmin ? node[t].min : nmin;
    return ;
    }
    if(node[t].l == node[t].r - 1) return;
    int mid = (node[t].l + node[t].r) >> 1;
    if(l >= mid)
    query(t
    << 1 | 1, l, r);
    else if(r <= mid)
    query(t
    << 1, l, r);
    else
    {
    query(t
    << 1, l, mid);
    query(t
    << 1 | 1, mid, r);
    }
    }
    int main()
    {
    int n, q, i;
    //freopen("data.in", "r", stdin);
    scanf("%d%d", &n, &q);
    for(i = 1; i <= n; i++)
    scanf(
    "%d", &num[i]);
    creat(
    1, 1, n);
    while(q--)
    {
    int x, y;
    scanf(
    "%d%d", &x, &y);
    if(x == y)
    {
    printf(
    "0\n");
    continue;
    }
    nmax
    = -inf; nmin = inf;
    query(
    1, x, y);
    printf(
    "%d\n", nmax - nmin);
    }
    return 0;
    }
  • 相关阅读:
    初探 Redis 客户端 Lettuce:真香!
    vscode 代码中查找并替换为换行符
    Jenkins Kubernetes插件添加 云
    Jenkins kubernetes插件的原理
    jenkins pipeline实现自动构建并部署至k8s
    python3 requests中的 stream参数
    rsync 开启用户密码认证
    rancher1版本 基本使用
    nginx http跳https
    sed合并多条指令修改文本
  • 原文地址:https://www.cnblogs.com/vongang/p/2132804.html
Copyright © 2011-2022 走看看