欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Super Mario 【HDU - 4417】【可持久化线段树】

程序员文章站 2024-03-03 16:36:46
...

题目链接


   处理不好就要T系列……因为去取upper_bound()的时候,可能会出现出现下角标为0的现象,这在线段树中是不允许的!

   然后就是处理的思路了,之前也做了区间第K大的数,这次来做区间K价值大的一下数的数目,不妨就对价值进行看作区间的处理,然后不断的去持久化,按照输入去更新即可。


#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdlib>
#include <ctime>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define MP(a, b) make_pair(a, b)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 1e5 + 7;
int N, M, a[maxN], b[maxN], root[maxN], cnt, lson[maxN*20], rson[maxN*20], siz[maxN*20];
void buildTree(int &k, int l, int r)
{
    k = ++cnt;
    siz[k] = 0;
    if(l == r) return;
    int mid = HalF;
    buildTree(lson[k], l, mid);
    buildTree(rson[k], mid + 1, r);
}
void update(int old, int &now, int l, int r, int pos)
{
    now = ++cnt;
    siz[now] = siz[old];    lson[now] = lson[old];  rson[now] = rson[old];
    if(l == r)
    {
        siz[now]++;
        return;
    }
    int mid = HalF;
    if(pos <= mid) update(lson[old], lson[now], l, mid, pos);
    else update(rson[old], rson[now], mid + 1, r, pos);
    siz[now] = siz[lson[now]] + siz[rson[now]];
}
int query(int old, int now, int l, int r, int k)
{
    if(k >= r) return siz[now] - siz[old];
    int mid = HalF;
    if(k > mid) return siz[lson[now]] - siz[lson[old]] + query(rson[old], rson[now], mid + 1, r, k);
    else return query(lson[old], lson[now], l, mid, k);
}
int main()
{
    int T;  scanf("%d", &T);
    for(int Cas=1; Cas<=T; Cas++)
    {
        cnt = 0;
        scanf("%d%d", &N, &M);
        for(int i=1; i<=N; i++)
        {
            scanf("%d", &a[i]);
            b[i] = a[i];
        }
        sort(b + 1, b + N + 1);
        int diff = (int)(unique(b + 1, b + N + 1) - b - 1);
        buildTree(root[0], 1, diff);
        for(int i=1; i<=N; i++)
        {
            int pos = (int)(lower_bound(b + 1, b + diff + 1, a[i]) - b);
            update(root[i-1], root[i], 1, diff, pos);
        }
        printf("Case %d:\n", Cas);
        while(M--)
        {
            int l, r, k;    scanf("%d%d%d", &l, &r, &k);
            l++;    r++;
            int pos = (int)(upper_bound(b + 1, b + diff + 1, k) - b);
            if(pos > diff) printf("%d\n", r - l + 1);
            else if(pos <= 1) printf("0\n");
            else printf("%d\n", query(root[l-1], root[r], 1, diff, pos-1));
        }
    }
    return 0;
}

 

相关标签: 可持久化线段树