双指针笔记

ykj12 2023-12-02 18:57:30 2023-12-02 19:28:52 3

尺取法

#include<bits/stdc++.h>

using namespace std;


const int N = 1e6 + 10;
int a[N];

int main()
{
	int sum = 0;
	int n, c;
	scanf ("%d%d", &n, &c);
	for (int i = 1; i <= n; i++) {
		scanf ("%d", &a[i]);
	}
	int l = 1, r = 1;
	sort (a + 1, a + 1 + n);
	for (int i = 1; i <= n; i++) {
		int b = a[i] - c;
		while (a[l] < b && l <= n) {
		    l++;
		} 
		while (a[r] <= b && r <= n) {
			r++;
		}
		sum += r - l;
	}
	printf ("%d\n", sum);
	return 0;
}

luogu P1638 逛画展

#include<bits/stdc++.h>

using namespace std;

int n, m;
const int N = 1e6 + 10;
int a[N];
int sum[N];
int num;

int main()
{
	int l = 1, r = 1;
	scanf ("%d%d", &n, &m);
	for (int i = 1; i <= n; i ++) {
		scanf ("%d", &a[i]);
	}
	int ans = 2000000;
	int al, ar;//最优区间 
	while (l <= r and r <= n + 1) {
		if (num < m) {//还没有选够  没有看完 
			r++;
			sum[a[r - 1]]++;//左闭右开区间 
			if (sum[a[r - 1]] == 1) num++;   
		}
		else {
			//num == m m个画家全部看完了
			if (ans > r - l) {
				//打擂台
				al = l;
				ar = r - 1;
				ans = r - l; 
			}
			//立刻更新区间(向右移动
			sum[a[l]]--;
			if (sum[a[l]] == 0) num--;
			l++; 
		}
	}
	printf ("%d %d\n", al, ar);
	return 0;
}

{{ vote && vote.total.up }}

共 1 条回复

ykj03 大懒虫

66666666666666666666666663