跳到正文

个人记录

国庆CSP-S #1 T4 题解

Jinzixun约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月14日
篇幅
约 2 分钟

版本

  1. v1当前

T4 题解

题意简述

求一个最长区间使得区间众数不唯一,输出最前的区间左右端点。

题目解法

CF1446D1。

有个结论:答案区间的众数中必定包含整个数列的众数。

证明一下:假设当前更新的答案为区间 l∼rl\sim r,且众数中没有全局众数,众数数量为 VV,那么我们可以通过左右扩展区间,使得将全局众数数量增加到比 VV 大,这样就更优。

接下来就简单了,考虑到答案区间一定包含整个数列的众数,那么只要枚举第二个众数,每次扫一遍记录即可。

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 5;
int n, zs, ans = -1, ansl, ansr, a[N], t[N], v[N];
bool f;
signed main(){
	scanf("%lld", &n);
	for(int i = 1; i <= n; i++){
		scanf("%lld", &a[i]);
		if(i > 2 && a[i] != a[i - 1])	f = true;
		t[a[i]]++;
		if(t[a[i]] > t[zs])	zs = a[i];//记录众数
	}
	if(!f){
		printf("-1");
		return 0;
	}//所有数一样无解
	for(int i = 1; i <= 200; i++){
		if(i == zs)	continue;
		int cnt = n;
		memset(v, -1, sizeof(v));//注意清空
		v[n] = 0;
		for(int j = 1; j <= n; j++){
			if(a[j] == zs)	cnt++;
			if(a[j] == i)	cnt--;
			if(v[cnt] == -1)	v[cnt] = j;
			else{
				if(j - v[cnt] > ans || (j - v[cnt] == ans && ansl > v[cnt])){
					ans = j - v[cnt];
					ansl = v[cnt];
					ansr = j;
				}
			}
		}
	}
	printf("%lld %lld", ansl + 1, ansr);
	return 0;
}
原文