牛客网暑期ACM多校训练营(第一场)J Different Integers(思维 + 树状数组)

链接: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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hhjian6666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值