mex

Time Limit: 20 Sec  Memory Limit: 128 MB
[Submit][Status][Discuss]

Description

  有一个长度为n的数组{a1,a2,...,an}。m次询问,每次询问一个区间内最小没有出现过的自然数。

Input

  第一行n,m。
  第二行为n个数。
  从第三行开始,每行一个询问l,r。

Output

  一行一个数,表示每个询问的答案。

Sample Input

  5 5
  2 1 0 2 1
  3 3
  2 3
  2 4
  1 2
  3 5

Sample Output

  1
  2
  3
  0
  3

HINT

  1<=n,m<=200000, 0<=ai<=1e9

Solution

  首先,权值>n的显然是没有用的,最多排满1~n。然后我们直接使用莫队,对权值分块,查询的时候看一下这个块里面权值数是否满了,即可做到O(sqrt(n))的查询。

Code

 #include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
using namespace std;
typedef long long s64; const int ONE = ;
const int INF = ; int n,m,Q,num;
int a[ONE],block[ONE];
int Ans[ONE];
int C[ONE],Bc[ONE]; struct power
{
int id;
int l,r;
}oper[ONE]; int cmp(const power &a,const power &b)
{
if(block[a.l] != block[b.l]) return block[a.l] < block[b.l];
return a.r < b.r;
} int get()
{
int res=,Q=; char c;
while( (c=getchar())< || c>)
if(c=='-')Q=-;
if(Q) res=c-;
while((c=getchar())>= && c<=)
res=res*+c-;
return res*Q;
} void increa(int x) {if(x>n) return; C[x]++; if(C[x]==) Bc[block[x]]++;}
void reduce(int x) {if(x>n) return; C[x]--; if(C[x]==) Bc[block[x]]--;} int Query()
{
int pos = ;
for(int i=;i<=num;i++)
if(Bc[i] < Q) {pos = i; break;}
for(int i=(pos-)*Q+;i<=n+;i++)
if(!C[i])
return i-;
} int main()
{
n=get(); m=get();
Q = sqrt(n); num = (n-)/Q+;
for(int i=;i<=n;i++)
a[i] = get()+, block[i] = (i-)/Q+;
for(int i=;i<=m;i++)
{
oper[i].id = i;
oper[i].l = get(); oper[i].r = get();
} sort(oper+, oper+m+, cmp); int l = , r = ;
for(int i=;i<=m;i++)
{
while(r < oper[i].r) increa(a[++r]);
while(oper[i].l < l) increa(a[--l]);
while(r > oper[i].r) reduce(a[r--]);
while(oper[i].l > l) reduce(a[l++]);
Ans[oper[i].id] = Query();
} for(int i=;i<=m;i++)
printf("%d\n", Ans[i]);
}

最新文章

  1. HDU4010 (动态树)
  2. JS 跨源请求
  3. eclipse 创建项目时出现appcompat_v7?
  4. REPL LOG
  5. NSDate使用
  6. http://my.oschina.net/u/2007041/blog/508520
  7. zzuoj 10409 10409: D.引水工程
  8. COCO-Android开发框架公布
  9. CSU 1640 机智的刷题方式
  10. (简单) FZU 1686 神龙的难题 , DLX+可重复覆盖。
  11. 常用的一些js和css
  12. thinkphp后台ajaxReturn提示下载的问题
  13. Django+Bootstrap+Mysql 搭建个人博客(二)
  14. iOS学习笔记之异步图片下载
  15. Codeforces 734E Anton and Tree(缩点+树的直径)
  16. HttpUrlConnection使用详解--转
  17. Java-web-j2e学习建议路线【转】
  18. mybatis中调用游标,存储过程,函数
  19. Scala的符号入门
  20. Oracle 物化视图创建以及常见问题

热门文章

  1. UVA725 Division (暴力求解法入门)
  2. Alpha 冲刺报告(4/10)
  3. LintCode-88.最近公共祖先
  4. open-stf 安装篇(linux)
  5. 什么是Oracle的分区表 (转 作者 陈字文)
  6. Matlab 中的varargin/nargin varargout/nargout
  7. concurrenthashmap jdk1.8
  8. [OS] CPU调度
  9. html5 js canvas中画星星的函数
  10. SQL查询数据总结