[FJOI 2016] 神秘数

[题目链接]

         https://www.lydsy.com/JudgeOnline/problem.php?id=4408

[算法]

         首先考虑一组询问怎样做 :

         将数组按升序排序 , 假设我们现在可以表示出[1 , x]范围的数 , 加入一个数Ai , 则Ai必须满足 :

         Ai <= x + 1

         若不满足 , 答案即为(x + 1)

         如何处理多组询问呢?

         考虑建立可持久化线段树 , 维护一段区间中小于或等于某个数的数的权值和

         设当前答案为ans

         在可持久化线段树中查询区间[l , r]中 <= ans的数的和x

         若x >= ans , 则ans = x + 1

         否则答案为(ans + 1)

         时间复杂度 : O(NlogN ^ 2)

[代码]

        

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const int N = 1e5 + 10;

int n , m;
int a[N] , rt[N];

struct Presitent_Segment_Tree
{
        int sz;
        int lc[N * 40] , rc[N * 40] , sum[N * 40];
        Presitent_Segment_Tree()
        {
                sz = 0;        
        }        
        inline void modify(int &now , int old , int l , int r , int x , int value)
        {
                now = ++sz;
                lc[now] = lc[old] , rc[now] = rc[old];
                sum[now] = sum[old] + value;
                if (l == r) return;
                int mid = (l + r) >> 1;
                if (mid >= x) modify(lc[now] , lc[old] , l , mid , x , value);
                else modify(rc[now] , rc[old] , mid + 1 , r , x , value);
        }
        inline int query(int rt1 , int rt2 , int l , int r , int ql , int qr)
        {
                if (l == ql && r == qr)
                        return sum[rt1] - sum[rt2];
                int mid = (l + r) >> 1;
                if (mid >= qr) return query(lc[rt1] , lc[rt2] , l , mid , ql , qr);
                else if (mid + 1 <= ql) return query(rc[rt1] , rc[rt2] , mid + 1 , r , ql , qr);
                else return query(lc[rt1] , lc[rt2] , l , mid , ql , mid) + query(rc[rt1] , rc[rt2] , mid + 1 , r , mid + 1 , qr);
        }
} PST;

template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); }
template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); }
template <typename T> inline void read(T &x)
{
    T f = 1; x = 0;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
    for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
    x *= f;
}

int main()
{
        
        read(n); 
        for (int i = 1; i <= n; ++i) read(a[i]);
        for (int i = 1; i <= n; ++i) PST.modify(rt[i] , rt[i - 1] , 1 , (int)1e9 , a[i] , a[i]);
        read(m);
        while (m--)
        {
                int l , r;
                read(l); read(r);
                 int ans = 1 , res = 1;
                while (true)
                {
                        res = PST.query(rt[r] , rt[l - 1] , 1 , (int)1e9 , 1 , ans);
                        if (res >= ans) ans = res + 1;
                        else break;        
                }        
                printf("%d\n" , ans);
        }
        
        return 0;
    
}

 

posted @ 2019-03-15 23:01  evenbao  阅读(209)  评论(0编辑  收藏  举报