[双指针]Car Show 2022牛客多校第9场 A

题目描述

There are nnn cities and mmm car styles in NIO Kingdom. According to the investigations, for the iii-th city, cars of style TiT_iTi​ are the most popular.

Now there will be a car show in NIO Kingdom, and the person in charge wants to choose an integer interval [l,r][l,r][l,r] (1≤l≤r≤n)(1\le l \le r \le n)(1≤l≤r≤n) and let the cities whose indices are in this interval hold the show jointly. And to manifest the variety of the cars, every style should occur at least once among the most popular styles in the host cities. Determine the number of integer intervals satisfying the constraint mentioned before.

输入描述:

The first line contains two integers nnn and mmm (1≤m≤n≤100 000)(1 \le m \le n \le 100\,000)(1≤m≤n≤100000), denoting the number of cities and the number of car styles respectively.

The second line contains nnn integers T1,T2,⋯ ,TnT_1, T_2, \cdots, T_nT1​,T2​,⋯,Tn​ (1≤Ti≤m)(1 \le T_i \le m)(1≤Ti​≤m), denoting the most popular styles.

输出描述:

Output one line containing one integer, denoting the answer.

示例1

输入

5 3
1 2 3 2 1

输出

5

说明

For the sample case, the 555 intervals are [1,3],[1,4],[1,5],[2,5],[3,5][1, 3], [1, 4], [1, 5], [2, 5], [3, 5][1,3],[1,4],[1,5],[2,5],[3,5] respectively.

题意: 给出n和m以及一个长度为n的数组,这个数组中的数字都∈[1, m],问有多少个区间出现了这全部的m个数字。

分析: 可以用双指针求解,枚举左端点l,然后找到一个区间[l, r]满足出现了m个数字,此时r之后的位置都可以作为区间右端点,所以贡献加n-r+1,然后l右移1格,而r的位置显然是不减的,当l遍历到n结束得到最终答案。

具体代码如下:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <string>
using namespace std;

int a[100005], num[100005];

signed main()
{
	int n, k;
	cin >> n >> k;
	for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
	int cnt = 0;
	long long ans = 0;
	for(int l = 1, r = 0; l <= n; l++){
		while(cnt < k && r <= n){
			r++;
			if(num[a[r]] == 0) cnt++;
			num[a[r]]++;
		}
		ans+=n-r+1;
		num[a[l]]--;
		if(num[a[l]] == 0) cnt--;
	}
	cout << ans << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值