链接:https://www.nowcoder.com/acm/contest/139/J
题目描述
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.
题意:
数组从L往左,从R往右组成一个新的数组,在数组中有几个不一样的数
分析:
树状数组离线处理进行更新删除
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
const int N = 300010;
int n;
map<int,int>mp;
struct BIT
{
int c[N];
void init(int n)
{
for (int i=0;i<=2*n;i++) c[i]=0;
}
void add(int loc,int v)
{
while (loc<=2*n)
{
c[loc]+=v;
loc+=loc&(-loc);
}
}
int sum(int loc)
{
int ret=0;
while (loc){
ret+=c[loc];
loc-=loc&(-loc);
}
return ret;
}
}T;
struct node
{
int l,r,id;
bool operator <(const node&rhs) const{
//if (l==rhs.l) return r<rhs.r;
return r<rhs.r;
}
}query[1000000+10];
int ans[1000000+10];
int A[N];
int main()
{
while (scanf("%d",&n)!=EOF)
{
int q,w=0;
scanf("%d",&q);
mp.clear();
T.init(n);
for (int i=1;i<=n;i++)
{
scanf("%d",&A[i]);
A[n+i]=A[i];
}
int temp;
for (int i=0;i<q;i++)
{
scanf("%d%d",&query[i].l,&query[i].r);
query[i].id=i;
temp=query[i].l;
query[i].l=query[i].r;
query[i].r=n+temp;
}
sort(query,query+q);
int cur=1;
for (int i=0;i<q;i++){
for(int j=cur;j<=query[i].r;j++){
if (mp.find(A[j])!=mp.end()){
T.add(mp[A[j]],-1);
}
T.add(j,1);
mp[A[j]]=j;
}
cur=query[i].r+1;
ans[query[i].id]=(T.sum(query[i].r)-T.sum(query[i].l-1));
}
for (int i=0;i<q;i++){
printf("%d\n",ans[i]);
}
}
return 0;
}