1. 程式人生 > 實用技巧 >CSUST 2009-Longest Subarray(佇列的應用)

CSUST 2009-Longest Subarray(佇列的應用)

題目連結:http://acm.csust.edu.cn/problem/2009
CSDN食用連結:https://blog.csdn.net/qq_43906000/article/details/107664641
Description

You are given two integers \(C\),\(K\) and an array of \(N\) integers \(a_1,a_2,\cdots,a_N\)It is guaranteed that the value of \(a_i\) is between \(1\) to \(C\)

We define that a continuous subsequence \(a_{l},a_{l+1},...,a_r(l \leq r)\)

of array a is a good subarray if and only if the following condition is met:
\(\forall x\in [1,C],\sum_{i=l}^{r}[a_i=x]\leq K\)

It implies that if a number appears in the subarray, it will appear no greater than \(K\) times.

You should find the longest good subarray and output its length. Or you should print \(0\)

if you cannot find any.

Input
Each case starts with a line containing three positive integers \(N,K,C (1 \leq N,K,C \leq 300000)\)

The second line contains \(N\) integer \(a_1,a_2,\cdots a_N(1\leq a_i\leq C)\)

Output
For each test case, output one line containing an integer denoting the length of the longest good subarray.

Sample Input 1
5 1 3
1 2 3 1 2

Sample Output 1
3

emmm,CSUSTOJ為數不多的幾道英文題面QWQ,實際上挺簡單的。

題目大意:讓你找到一個最長的的連續子序列,使得這個子序列中每個元素出現的次數小於等於\(K\)

既然是找連續的,那麼這個就很簡單了,一旦碰到出現次數大於\(K\)的,我們將前面的元素一直往外拋就完事了,這不就是個佇列的問題了嘛。

以下是AC程式碼:

#include <bits/stdc++.h>
using namespace std;

const int mac=3e5+10;

int vis[mac],a[mac];

int main(int argc, char const *argv[])
{
	int n,k,c;
	scanf ("%d%d%d",&n,&k,&c);
	for (int i=1; i<=n; i++)
		scanf ("%d",&a[i]);
	int ans=0,j=1;
	for (int i=1; i<=n; i++){
		vis[a[i]]++;
		while (vis[a[i]]>k){
			vis[a[j]]--; j++;
		}
		ans=max(ans,i-j+1);
	}
	printf("%d\n",ans);
	return 0;
}