Codeforces 368B Sereja and Suffixes 线段树按值建树

本文介绍了一个经典的算法问题——Sereja与后缀问题,该问题要求在给定的整数数组中,对于一系列指定的起始位置,找出从该位置到数组末尾的不同元素数量。文中提供了一种使用线段树进行预处理的方法,以及一种更高效的DP解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门:点击打开链接

B. Sereja and Suffixes
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ..., n. Formally, he want to find the number of distinct numbers among ali, ali + 1, ..., an.?

Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each li.

Input

The first line contains two integers n and m (1 ≤ n, m ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the array elements.

Next m lines contain integers l1, l2, ..., lm. The i-th line contains integer li (1 ≤ li ≤ n).

Output

Print m lines — on the i-th line print the answer to the number li.

Sample test(s)
Input
10 10
1 2 3 4 1 2 3 4 100000 99999
1
2
3
4
5
6
7
8
9
10
Output
6
6
6
6
6
5
4
3
2
1

题意:给出一个数列长度为n,m次询问,每次输入一个l,要求输出区间[l,n]中有多少个不同的数。

思路:用线段数进行预处理,处理出每个位置到n的这个区间内不同数的个数。将线段树按值建树,从数列的尾部往前面扫描,对于数列的每一个数a[i],在线段树中,如果a[i]处为0的话,把它改成1,否则不变,然后再对整个线段树的区间求和,就是第i个位置的答案。

代码:

#include<cstdio>
#include<cstring>
#define maxn 100005
int sum[maxn << 2];
void update(int id, int L, int R, int pos)
{
	if (L == R) sum[id] = 1;
	else
	{
		int mid = (L + R) >> 1;
		if (pos <= mid) update(id << 1, L, mid, pos);
		else update(id << 1 | 1, mid + 1, R, pos);
		sum[id] = sum[id << 1] + sum[id << 1 | 1];
	}
}
int a[maxn];
int ans[maxn];
int main()
{
	int n, m;
	scanf("%d %d", &n, &m);
	for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
	memset(sum, 0, sizeof(sum));
	for (int i = n; i >= 1; i--)
	{
		update(1, 1, 100000, a[i]);
		ans[i] = sum[1];
	}
	while (m--)
	{
		int x;
		scanf("%d", &x);
		printf("%d\n", ans[x]);
	}
	return 0;
}

还有就是DP的做法,时间复杂度仅为O(n),dp[i]=dp[i+1]+(vis[ai]]);

用bool vis[i]记录是否出现过。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值