G1: Yunli‘s Subarray Queries (easy version)(1900)(定长区间众数)

思路:因为是定长区间,因此我们可以利用滑动窗口维护定长区间的众数的数量

AC代码:

cpp 复制代码
#include<bits/stdc++.h>

using namespace std;

typedef long long ll;
const int MOD = 998244353;
const int N = 2e5 + 10;

ll a[N];
ll b[N];//前i个数的相同的数的最大值
int main()
{
	
	int t;
	cin >> t;
	while(t --){
		ll n, k, q;
		cin >> n >> k >> q;
		for(int i = 1; i <= n; i ++)
		{
			cin >> a[i];
			a[i] -= i;
		}
		//求每个区间为k的区间众数的数量
		//看到定长想到滑动区间
		map<ll, ll>ma, cnt;//记录数量
		for(int i = 1; i <= n; i ++)
		{
			if(cnt.count(ma[a[i]]))//相当于对右边界进行操作
			{
				cnt[ma[a[i]]] -= 1;
				if(!cnt[ma[a[i]]]) cnt.erase(ma[a[i]]);
			}
			ma[a[i]] += 1;
			cnt[ma[a[i]]] += 1;
			//前k个数还没到达窗口最远
			if(i < k) continue;
			//因为区间长度已经确定为k了,因此我们确定了左区间,右区间也随之确定了
			b[i - k + 1] = cnt.rbegin() ->first;//代表反向开始的第一个元素,即众数
		//	cout << b[1] << "sss" << endl;
			cnt[ma[a[i - k + 1]]] -= 1;//因为开始窗口滑动了因此也需要考虑左边界了
			if(!cnt[ma[a[i - k + 1]]]) cnt.erase(ma[a[i - k + 1]]);
			ma[a[i - k + 1]]  -= 1;//左边界ma也要参与了
			if(ma[a[i - k + 1]]) cnt[ma[a[i - k + 1]]] += 1;
		}
		while(q --){
			ll l, r;
			cin >> l >> r;
			cout << k - b[l] << endl;
		}
	}
	return 0;
}
相关推荐
练习时长一年38 分钟前
Leetcode热题100(跳跃游戏 II)
算法·leetcode·游戏
小白菜又菜6 小时前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
wuhen_n7 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo7 小时前
leetcode 2483
数据结构·算法·leetcode
Xの哲學8 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢8 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
油泼辣子多加9 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习
Aaron15889 小时前
AD9084和Versal RF系列具体应用案例对比分析
嵌入式硬件·算法·fpga开发·硬件架构·硬件工程·信号处理·基带工程
laocooon5238578869 小时前
插入法排序 python
开发语言·python·算法
wuhen_n10 小时前
LeetCode -- 1:两数之和(简单)
javascript·算法·leetcode·职场和发展