链接: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.
将询问按照r排序,然后依次将数放进数组,如果这个数出现过 将之前位置清零,当前位置+1;如果这个是没有出现过
就在当前位置+1
求 L-R 中有多少种数,这里把 1-L 中把一种数最后出现的位置作为贡献值,这样 Sum(R) - Sum(L-1) 就有正确性。注意当我们更新到R时, Sum(L)不是 1-L中的数的个数(只能表示在1-R中只出现在1-L中的数有多少种),Sum(R)才是表示 1-R中有多少种数。
//Sinhaeng Hhjian
#include<stdio.h>
#include<string.h>
#include<map>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
struct node{
int l, r, id;
}st[maxn];
int n, q, a[maxn*2], c[maxn*2], book[maxn*2], ans[maxn];
int cmp(node a, node b){
return a.r<b.r;
}
void add(int x, int d){
for(int i=x;i<=n*2;i+=(i&(-i)))
c[i]+=d;
}
int query(int x){
int sum=0;
for(int i=x;i;i-=(i&(-i)))
sum+=c[i];
return sum;
}
int main(){
while(~scanf("%d%d", &n, &q)){
for(int i=1;i<=n;i++){
scanf("%d", &a[i]);
a[n+i]=a[i];
}
for(int i=1;i<=q;i++){
int l, r;
scanf("%d%d", &l, &r);
st[i].l=r;st[i].r=n+l;st[i].id=i;
}
sort(st+1, st+q+1, cmp);
memset(c, 0, sizeof(c));
memset(book, 0, sizeof(book));
int cur=1;
for(int i=1;i<=q;i++){
while(cur<=st[i].r && cur<=n*2){
if(book[a[cur]])
add(book[a[cur]], -1);
book[a[cur]]=cur;
add(book[a[cur]], 1);
cur++;
}
ans[st[i].id]=query(st[i].r)-query(st[i].l-1);
}
for(int i=1;i<=q;i++)
printf("%d\n", ans[i]);
}
return 0;
}