【洛谷P4587】神秘数【主席树】

题目大意:

题目链接:https://www.luogu.org/problem/P4587
一个可重复数字集合 S S S的神秘数定义为最小的不能被 S S S的子集的和表示的正整数。
现给定 n n n个正整数 a [ 1 ] . . a [ n ] a[1]..a[n] a[1]..a[n] m m m个询问,每次询问给定一个区间 l , r l,r l,r,求由 a [ l ] , a [ l + 1 ] , … , a [ r ] a[l],a[l+1],…,a[r] a[l],a[l+1],,a[r]所构成的可重复数字集合的神秘数。


思路:

假设现在选择的数字可以构成的区间为 [ 1 , x ] [1,x] [1,x],那么答案 a n s = x + 1 ans=x+1 ans=x+1
那么如果在区间 [ l i , r i ] [l_i,r_i] [li,ri]的数字内仍然有不超过 a n s ans ans数字没有选择,假设这些数字的和为 s u m sum sum,那么 [ 1 , x + s u m ] [1,x+sum] [1,x+sum]内的数字全部都可以被表示出来。因为对于 [ 1 , x ] [1,x] [1,x]中的任意一个数 y y y,都必然可以组成 y + s u m y+sum y+sum
所以此时的答案 a n s = x + s u m + 1 ans=x+sum+1 ans=x+sum+1。也就是 a n s = a n s ′ + s u m ans=ans'+sum ans=ans+sum
也就是说,如果此时不超过 a n s ans ans的数的和 s u m ≥ a n s sum\geq ans sumans,那么就可以更新 a n s = s u m + 1 ans=sum+1 ans=sum+1。否则 a n s ans ans一定不可以被表示出来, a n s ans ans就是最终答案。
求区间 [ l , r ] [l,r] [l,r]不超过 a n s ans ans可以直接用主席树搞定。


代码:

#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=100010;
int n,m,tot,l,r,ans,sum,root[N];

struct Tree
{
	int lc,rc,sum;
}tree[N*35];

int read()
{
	int d=0;
	char ch=getchar();
	while (!isdigit(ch)) ch=getchar();
	while (isdigit(ch))	
		d=(d<<3)+(d<<1)+ch-48,ch=getchar();
	return d;
}

int insert(int now,int l,int r,int val)
{
	int p=++tot;
	tree[p]=tree[now];
	tree[p].sum+=val;
	if (l==r) return p;
	int mid=(l+r)>>1;
	if (val<=mid) tree[p].lc=insert(tree[now].lc,l,mid,val);
		else tree[p].rc=insert(tree[now].rc,mid+1,r,val);
	return p;
}

int ask(int nowl,int nowr,int l,int r,int p,int q)
{
	if (l==p && r==q) 
		return tree[nowr].sum-tree[nowl].sum;
	int mid=(l+r)>>1;
	if (q<=mid) return ask(tree[nowl].lc,tree[nowr].lc,l,mid,p,q);
	if (p>mid) return ask(tree[nowl].rc,tree[nowr].rc,mid+1,r,p,q);
	return ask(tree[nowl].lc,tree[nowr].lc,l,mid,p,mid)+ask(tree[nowl].rc,tree[nowr].rc,mid+1,r,mid+1,q);
}

int main()
{
	n=read();
	for (int i=1;i<=n;i++)
		root[i]=insert(root[i-1],1,1e9,read());
	m=read();
	while (m--)
	{
		l=read(); r=read();
		ans=1;
		while ((sum=ask(root[l-1],root[r],1,1e9,1,ans))>=ans) ans=sum+1;
		printf("%d\n",ans);
	}
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值