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;
}
相关推荐
!停11 分钟前
C语言单链表
c语言·数据结构·算法
闻缺陷则喜何志丹22 分钟前
【回文 字符串】3677 统计二进制回文数字的数目|2223
c++·算法·字符串·力扣·回文
Tisfy28 分钟前
LeetCode 0085.最大矩形:单调栈
算法·leetcode·题解·单调栈
mit6.82430 分钟前
出入度|bfs|状压dp
算法
hweiyu0030 分钟前
强连通分量算法:Kosaraju算法
算法·深度优先
源代码•宸31 分钟前
Golang语法进阶(定时器)
开发语言·经验分享·后端·算法·golang·timer·ticker
mit6.82437 分钟前
逆向思维|memo
算法
机器学习之心39 分钟前
MATLAB灰狼优化算法(GWO)改进物理信息神经网络(PINN)光伏功率预测
神经网络·算法·matlab·物理信息神经网络
代码游侠42 分钟前
学习笔记——ESP8266 WiFi模块
服务器·c语言·开发语言·数据结构·算法
倦王43 分钟前
力扣日刷26110
算法·leetcode·职场和发展