跳到正文

个人记录

Diamond Collector S题解

yingshi1119约 1 分钟
原文
文章信息与版本

文章信息

发布
2024年7月13日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1

题面大意

对于一个序列 aa 将其分割出两个不重合的字段,使得在峰差不大于 kk 的情况下,总长度最大。

我的思路:

发现解题难点在于 不重合 ,因此考虑分割端点,两侧用双指针维护,时间复杂度 n×log(n)n\times log(n)。

更加优秀的解法

我的思路的要点在于二分的单调性,因为若左段的左端不变,左段越长,右段肯定不劣,所以考虑对从每一个节点能延伸的最长长度做记录,时间复杂度 O(n)O(n)。

AC代码:

C++
#include<bits/stdc++.h>
using namespace std;
const int N=5e4+10;
int a[N],c[N],r=2,pre,ans;
int main()
{
    ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
	int n,k;
    cin>>n>>k;
    for(int i=1;i<=n;i++) cin>>a[i];
    sort(a+1,a+n+1);
    for(int i=1;i<=n;i++)
	{
        while(a[r]<=a[i]+k&&r<=n) r++;
        c[r]=max(r-i,c[r]);
        pre=max(pre,c[i]);
        ans=max(ans,pre+r-i);
        //if(r==n) break;
    }
    cout<<ans;
    return 0;
}
原文