D-query 莫队算法
Given a sequence of n numbers a1, a2, ..., an and a number of d-queries. A d-query is a pair (i, j) (1 ≤ i ≤ j ≤ n). For each d-query (i, j), you have to return the number of distinct elements in the subsequence ai, ai+1, ..., aj.
Input
- Line 1: n (1 ≤ n ≤ 30000).
- Line 2: n numbers a1, a2, ..., an (1 ≤ ai ≤ 106).
- Line 3: q (1 ≤ q ≤ 200000), the number of d-queries.
- In the next q lines, each line contains 2 numbers i, j representing a d-query (1 ≤ i ≤ j ≤ n).
Output
- For each d-query (i, j), print the number of distinct elements in the subsequence ai, ai+1, ..., aj in a single line.
Example
Input 5 1 1 2 1 3 3 1 5 2 4 3 5 Output 3 2 3
题意: 给定一个有N个方格组成的一行, 每个格子有特定的颜色(颜色由编号表示), 题目给定Q个询问, 每次询问[i, j]的不同颜色总数.
分析: 莫队算法裸题. 主席树也可以做. 后者做法请百度.
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<iomanip>
#include<stdlib.h>
#include<cstdio>
#include<string>
#include<string.h>
#include<set>
#include<map>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int INF = 0x7fffffff;
const int MAX_N = 3e4+5;
const int MAX_V = 1e6+5;
const int MAX_M = 0;
const int MAX_Q = 2e5+5;
void show(string a, int val){
cout<<a<<": "<<val<<endl;
}
int N, Q;
int Mo[MAX_N];
struct node{
int l, r, id;
node(int l, int r, int id): l(l), r(r), id(id){}
node(){}
}nd[MAX_Q];
bool cmp(node a, node b){
int ma = Mo[a.l], mb = Mo[b.l];
if(ma != mb) return ma<mb;
return a.r<b.r;
}
// label 记录某数的最后节点 pre记录某数之前的相同数的位置, val记录当前点的权值
int label[MAX_V], pre[MAX_N], val[2*MAX_N], res[MAX_Q];
int v[MAX_N];
void update(int k, int& ans, bool mod){
//expand
if(mod){
ans += ++val[k]-val[pre[k]]--;
}
// shrink
else{
ans -= val[k]-- - ++val[pre[k]];
}
}
//Mo Algorithm
void MA(){
sort(nd, nd+Q, cmp);
int l = 1, r = 0;
int ans = 0;
for(int i=0; i<Q; i++){
int tl = nd[i].l, tr = nd[i].r;
while(tl<l){
update(--l,ans,true);
}
while(l<tl){
update(l++,ans,false);
}
while(tr<r){
update(r--,ans,false);
}
while(r<tr){
update(++r,ans,true);
}
res[nd[i].id] = ans;
}
}
int main(){
while(~scanf("%d",&N)){
memset(val, 0, sizeof val);
memset(pre, -1, sizeof pre);
memset(label, -1, sizeof label);
int a, b;
int st = sqrt(N*1.0+0.5);
for(int i=0; i<N; i++){
scanf("%d", &a);
v[i] = a;
//pre
if(label[a]==-1)
pre[i] = N+i;
else
pre[i] = label[a];
label[a] = i;
}
scanf("%d",&Q);
for(int i=0; i<Q; i++){
scanf("%d%d",&a,&b);
Mo[a-1] = (a-1)/st;
nd[i] = node(a-1, b-1, i);
}
MA();
for(int i=0; i<Q; i++)
printf("%d\n",res[i]);
}
}