题目背景
对应的选择、判断题:试题 - GESP 202509 C++ 四级 - 洛谷有题
题目描述
对于 k 个整数构成的数组 b1,b2,...,bk,如果对 1≤i<k 都有 bi+1=bi+1,那么称数组 b 是一个连续段。
给定由 n 个整数构成的数组 a1,a2,...,an,你可以任意重排数组 a 中元素顺序。请问在重排顺序之后,a 所有是连续段的子数组中,最长的子数组长度是多少?
例如,对于数组 1,0,2,4,可以将其重排为 4,0,1,2,有以下 10 个子数组:
4\],\[0\],\[1\],\[2\],\[4,0\],\[0,1\],\[1,2\],\[4,0,1\],\[0,1,2\],\[4,0,1,2
其中除 4,0,4,0,1,4,0,1,2 以外的子数组均是连续段,因此是连续段的子数组中,最长子数组长度为 3。
输入格式
第一行,一个正整数 n,表示数组长度。
第二行,n 个整数 a1,a2,...,an,表示数组中的整数。
输出格式
一行,一个整数,表示数组 a 重排顺序后,所有是连续段的子数组的最长长度。
输入输出样例
输入 #1复制
4
1 0 2 4
输出 #1复制
3
输入 #2复制
9
9 9 8 2 4 4 3 5 3
输出 #2复制
4
说明/提示
对于 40% 的测试点,保证 1≤n≤8。
对于所有测试点,保证 1≤n≤105,−109≤ai≤109。
代码实现:
cpp
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
unordered_map<long long, int> cnt;
vector<long long> nums;
for (int i = 0; i < n; i++)
{
long long x;
cin >> x;
cnt[x]++;
}
for (auto &p : cnt) nums.push_back(p.first);
sort(nums.begin(), nums.end());
int maxans = 1;
int l = 0;
for (int r = 0; r < nums.size(); r++)
{
while (nums[r] - nums[l] > r - l) l++;
maxans = max(maxans, r - l + 1);
}
cout << maxans;
return 0;
}