题目描述
Given a sequence of integers a1, a2, ..., an and q pairs of integers (l1, r1), (l2, r2), ..., (lq, rq), find count(l1, r1), count(l2, r2), ..., count(lq, rq) where count(i, j) is the number of different integers among a1, a2, ..., ai, aj, aj + 1, ..., an.
输入描述:
The input consists of several test cases and is terminated by end-of-file.
The first line of each test cases contains two integers n and q.
The second line contains n integers a1, a2, ..., an.
The i-th of the following q lines contains two integers li and ri.
输出描述:
For each test case, print q integers which denote the result.
示例1
输入
3 2
1 2 1
1 2
1 3
4 1
1 2 3 4
1 3
输出
2
1
3
备注:
* 1 ≤ n, q ≤ 105
* 1 ≤ ai ≤ n
* 1 ≤ li, ri ≤ n
* The number of test cases does not exceed 10.
题意:
给你n个数字,给你查询l,r,让你得出1-l 加上r-n里不同的数有几个。
POINT:
把数组扩充两倍,那么问题就变成了连续一段区间内不同的数有几个了。
那么可以用树状数组+离线做。
#include<iostream>
#include<stdio.h>
#include<cmath>
#include<vector>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 2e5+55;
int n;
int a[maxn];
int b[maxn];
struct node
{
int l,r;
int id;
int ans;
friend bool operator < (node a, node b)
{
return a.r<b.r;
}
}q[maxn];
int num[maxn];
void add(int x,int p)
{
if(x==0) return ;
for(;x<=n;x+=x&-x)
num[x]+=p;
}
int query(int x)
{
int ans=0;
for(;x>=1;x-=x&-x)
ans+=num[x];
return ans;
}
int pre[maxn];
bool cmd(node a,node b){
return a.id<b.id;
}
int main()
{
int qq;
while(~scanf("%d %d",&n,&qq)){
memset(num,0,sizeof num);
memset(pre,0,sizeof pre);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
b[n-i+1]=a[i];
}
for(int i=n;i>=1;i--){
b[n+n-i+1]=a[i];
}
for(int i=1;i<=qq;i++){
int l,r;scanf("%d%d",&l,&r);
q[i].l=n-l+1;
q[i].id=i;
q[i].r=n+n-r+1;
}
n=2*n;
sort(q+1,q+1+qq);
int now = 1;
for(int i=1;i<=n&&now<=qq;i++){
add(i,1);
add(pre[b[i]],-1);
pre[b[i]]=i;
while(q[now].r==i&&now<=qq){
q[now].ans=query(q[now].r)-query(q[now].l-1);
now++;
}
}
sort(q+1,q+1+qq,cmd);
for(int i=1;i<=qq;i++){
printf("%d\n",q[i].ans);
}
}
return 0;
}

本文介绍了一种解决区间不同整数查询问题的算法实现,通过树状数组和离线处理的方法,在给定一系列整数及查询对的情况下,快速计算出各查询区间内的不同整数数量。
 - J Different Integers (树状数组)&spm=1001.2101.3001.5002&articleId=81121398&d=1&t=3&u=89b68011b110497a8c76abb8d2570da4)
1412

被折叠的 条评论
为什么被折叠?



