滑动窗口(双指针)

发布时间 2023-12-21 19:08:18作者: viewoverlook

滑动窗口(双指针)

image.png

#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <array>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
typedef long long LL;
const int N = 1e5+10;
int n,k,c,a[N],q[N];
int main()
{	
	scanf("%d%d%d",&n,&k,&c);
	for(int i = 1; i <= n; i++) scanf("%d",&a[i]);
	int front = 1, rear = 0, ans = 0;
	for(int i = 1; i <= n; i++){
		while(front <= rear && a[q[rear]] <= a[i])
			--rear; 
		q[++rear] = i;
		if(i - c + 1 >= 1){
			if(a[q[front]] <= k) ++ans;
			if(q[front] == i - c + 1) ++front;
		}
	}
	printf("%d\n",ans);

	return 0;
}

image.png

#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <array>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
typedef long long LL;
const int N = 1e5+10;
int n, k, a[N];
LL s[N];
int main()
{	
	scanf("%d%d",&n,&k);
	for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
	for(int i = 1; i <= n; i++) s[i] = s[i - 1] + a[i];
	int x = 1, ans = 0;
	for(int i = 1; i <= n; i++){
		while(x <= n && s[x] - s[i - 1] <= k) ++x;
		ans = max(ans, x - i);
	}
	printf("%d\n",ans);
	
	return 0;
}

image.png

// Problem: C. They Are Everywhere
// Contest: Codeforces - Codeforces Round 364 (Div. 2)
// URL: https://codeforces.com/problemset/problem/701/C
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <array>
using namespace std;
#define x first
#define y second
typedef pair<int, int> PII;
typedef long long LL;
const int N = 1e5+10;
int n, c[256];
char s[N];
int main()
{	
	scanf("%d%s",&n,s + 1);
	int tot = 0;
	for(int i = 1; i <= n; i++)
		if(++c[s[i]] == 1)
			tot++;
	memset(c, 0, sizeof(c));
	int d = 0, ans = 1 << 30, x = 1;
	for(int i = 1; i <= n; i++)
	{
		while(x <= n && d < tot){
			if(++c[s[x]] == 1)
				++d;
			++x;
		}
		if(d == tot) ans = min(ans, x - i);
		if(--c[s[i]] == 0) --d;
	}
	printf("%d\n",ans);

	return 0;
}