codeforces 1247 B1 && B2 . TV Subscriptions (Easy && Hard Version) (尺取)

B1 && B2. TV Subscriptions (Easy && Hard Version)(尺取)

题目链接:codeforces 1247B2

题意:

   给出三个数n,k,d,(代表有n个数,k种不同的数),然后给出n个数,问连续相邻的d个数中,最少有多少种数.

举例:

16 9 8
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3                  答案为 5

16个数,有9种,在连续相邻的8个数中

1 - 8 有 7种不同的数,分别是 3  1  4  5  9  2  6

2 - 9 有 6种不同的数,分别是 1  4  5  9  2  6 4 

......

9 - 16 有5种不同的数,分别是 5  3  8  9  7

解题思路:

   典型尺取问题,数据段整体往后平移一个,当前面的数的个数减去之后为0,那么ans--,新增的数的个数如果不为0 ,那么ans不变,否则ans+1

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6+5;
int a[maxn], b[maxn];
typedef long long ll;
int main(){
	int t;
	cin >> t;
	while(t--){
		int n, k, d;
		cin >> n >> k >> d;
		int ans = d, x = 0;
		memset(a, 0, sizeof(a));
		for(int i = 1; i <= n ; i++){
			cin >> b[i];
			if(i < d){
				if(a[b[i]] == 0){
					x++;
				}
			}
			else{
				a[b[i-d]]--;
				if(a[b[i-d]] == 0){
					x--;
				}
				if(a[b[i]] == 0){
					x++;
				}
				if(ans > x){
					ans = x;
				}
			}
			a[b[i]]++;
		}
		cout << ans << endl;
	}
	return 0;
}
发布了204 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/error311/article/details/102787699
今日推荐