HDU 4747 Mex(线段树+思维题)

博客讨论了一种求序列所有连续子序列mex之和的问题,通过预处理和线段树实现,时间复杂度为3nlogn+n。提供了思路解析和代码示例。
摘要由CSDN通过智能技术生成

Problem Description
Mex is a function on a set of integers, which is universally used for impartial game theorem. For a non-negative integer set S, mex(S) is defined as the least non-negative integer which is not appeared in S. Now our problem is about mex function on a sequence.

Consider a sequence of non-negative integers {ai}, we define mex(L,R) as the least non-negative integer which is not appeared in the continuous subsequence from aL to aR, inclusive. Now we want to calculate the sum of mex(L,R) for all 1 <= L <= R <= n.

Input
The input contains at most 20 test cases.
For each test case, the first line contains one integer n, denoting the length of sequence.
The next line contains n non-integers separated by space, denoting the sequence.
(1 <= n <= 200000, 0 <= ai <= 10^9)
The input ends with n = 0.

Output
For each test case, output one line containing a integer denoting the answer.

Sample Input
3
0 1 3
5
1 0 2 0 1
0

Sample Output
5
24
Hint
For the first test case:
mex(1,1)=1, mex(1,2)=2, mex(1,3)=2, mex(2,2)=0, mex(2,3)=0,mex(3,3)=0.
1 + 2 + 2 + 0 +0 +0 = 5.

大致题意:给你一个长度为n的序列,让你求该序列的所有连续子序列的mex(i,j)的和,mex(i,j)表示,区间i到j内没有出现过的最小非负整数,与博弈中的mex定义一样。

思路:膜一发大佬的博客https://www.cnblogs.com/20143605–pcx/p/5723148.html
首先预处理出每一个ai下一个出现相同值的位置,用数组nex[]来保存。求出所有mex(1,i)的值,然后以之为节点建立一颗线段树,接下来我们将a[1]这个数从序列中删除,将叶子节点的维护信息更新为mex(2,i),以此类推,然后每更新一次便求一次和,总和即为答案。然后当我们删除a[i]时,假设下一个与a[i]值相同的位置是k,那么只有k以前的mex(i+1,j)会有影响,j< k,假如mex(i+1,j)的值小于a[i],那么删掉a[i]后对其也不影响,有影响的只有那些大于a[i]的mex(i+1,j),此外可知当我们固定了左端点a后mex(a,b)的值是单调不减的,所以我们需要修改的是一段连续的区间,所以我们需要找出最小的那个p,满足mex(i+1,p)大于a[i],且p< k,那么我们需要修改的便是[p,k-1]这么一段连续的区间,总的时间复杂度为3*nlogn+n(查询,修改,求和

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值