链接:https://www.nowcoder.com/acm/contest/139/J
来源:牛客网
莫队算法离线处理区间问题
满足已知[l,r]的结果,能在o(1)或者log 的时间内求出[l,r-1] [l,r+1] [l-1,r] [l+1,r]的结果
即可运用莫队算法来解决问题 总时间复杂度是n*sqrt(n) 或者增加一个log的乘积
题目描述
Given a sequence of integers a
1, a
2, ..., a
n and q pairs of integers (l
1, r
1), (l
2, r
2), ..., (l
q, r
q), find count(l
1, r
1), count(l
2, r
2), ..., count(l
q, r
q) where count(i, j) is the number of different integers among a
1, a
2, ..., a
i, a
j, a
j + 1, ..., a
n.
输入描述:
The input consists of several test cases and is terminated by end-of-file.1
The first line of each test cases contains two integers n and q.
The second line contains n integers a
, a2
, ..., an
.i
The i-th of the following q lines contains two integers l
and ri
.
输出描述:
For each test case, print q integers which denote the result.
备注:
* 1 ≤ n, q ≤ 105
i
* 1 ≤ a
≤ ni
* 1 ≤ l
, ri ≤ n
* The number of test cases does not exceed 10.
莫队算法离线处理区间问题
满足已知[l,r]的结果,能在o(1)或者log 的时间内求出[l,r-1] [l,r+1] [l-1,r] [l+1,r]的结果
即可运用莫队算法来解决问题 总时间复杂度是n*sqrt(n) 或者增加一个log的乘积
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=2e5+10; const int M=1e6+10; int n,t,blo;ll tmp; struct Node{int l,r,id;}q[N]; int ans[N];int a[N],num[M]; bool cmp(Node x,Node y){ if(x.l/blo!=y.l/blo) return x.l/blo<y.l/blo; return x.r<y.r; } void read(int &x) { int f=1;x=0;char s=getchar(); while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();} while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();} x*=f; } void add(int x){ num[a[x]]--; if(num[a[x]]==0) tmp--; } void Remove(int x){ if(num[a[x]]==0) tmp++; num[a[x]]++; } int main(){ int n,m; while(~scanf("%d%d",&n,&m)){ blo=sqrt(n);tmp=0; for(int i=1;i<=n;i++) read(a[i]),num[i]=0; for(int i=1;i<=m;i++){ read(q[i].l);read(q[i].r); q[i].l++,q[i].r--; q[i].id=i; } sort(q+1,q+m+1,cmp); int nl=1,nr=0,l,r;tmp=0; for(int i=1;i<=n;i++){ if(num[a[i]]==0) tmp++; num[a[i]]++; } int sum=tmp; for(int i=1;i<=m;i++){ l=q[i].l,r=q[i].r; if(l>r) {ans[q[i].id]=sum;continue;} while(l<nl) add(--nl); while(r>nr) add(++nr); while(l>nl) Remove(nl++); while(r<nr) Remove(nr--); ans[q[i].id]=tmp; } for(int i=1;i<=m;i++) printf("%d\n",ans[i]); } return 0; }