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;
}
相关推荐
昵称小白几秒前
栈与单调栈专题
开发语言·算法
心.c9 分钟前
RAG文档解析 - pypdf、LlamaParse、DeepDoc、SimpleDirectoryReader到底怎么选?
python·算法·ai
AI科技星10 分钟前
基于代数拓扑与等腰梯形素数对网格【乖乖数学】
人工智能·算法·决策树·机器学习·数学建模·数据挖掘·机器人
jghhh0118 分钟前
基于时差(TDOA)与 频差(FDOA) 的无源定位
算法
_深海凉_25 分钟前
LeetCode热题100-回文链表
算法·leetcode·链表
pursuit_csdn31 分钟前
力扣周赛 501
算法·leetcode·职场和发展
努力d小白33 分钟前
leetcode70.爬楼梯
算法
AbandonForce33 分钟前
LeetCode 滑动窗口个人思路详解
算法·leetcode·职场和发展
bnmoel36 分钟前
数据结构深度剖析顺序表:结构、扩容与增删查改全解析
c语言·数据结构·算法·顺序表
Liangwei Lin36 分钟前
LeetCode 45. 跳跃游戏 II
数据结构·算法·leetcode