【CF1157F】Maximum Balanced Circle

题目大意:给定一个长度为 N 的序列,求是否能够从序列中选出一个集合,使得这个集合按照特定的顺序排成一个环后,环上相邻的点之间的权值差的绝对值不超过 1。

题解:集合问题与序列顺序无关,因此可以先将序列排序。
可以发现,题目中描述的环,拆成序列之后应该满足 \(a_l,a_{l+1},...,a_{r},a_{r-1},...,a_{l+1}\) 的形态,即:除了 \(a_l,a_r\) 之外的其他所有值应该都有至少两个。因此,开一个桶记录一下每个元素出现的次数,并对原序列进行去重。可知,对于满足 \(1,2,2,...2,1\) 形态的序列中的任何一个 2 的位置的答案都是相同的。因此,考虑使用双指针法,每次都找到 1 出现的位置,统计答案并更新答案即可。

代码如下

#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+10;

int n,d[maxn],tot,cnt[maxn];

void read_and_parse(){
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d",&d[i]),++cnt[d[i]];
    sort(d+1,d+n+1);
    tot=unique(d+1,d+n+1)-d-1;
}

void solve(){
    int ans=cnt[d[1]],l=1,r=1;
    for(int i=1,j;i<=tot;i=j){
        j=i+1;
        int sum=cnt[d[i]];
        while(j<=tot&&d[j]-d[j-1]==1&&cnt[d[j]]>=2)sum+=cnt[d[j]],++j;
        int cr=j-1;
        if(j<=tot&&d[j]-d[j-1]==1)sum+=cnt[d[j]],cr=j;
        if(sum>ans)ans=sum,l=i,r=cr;
    }
    printf("%d\n",ans);
    for(int i=1;i<=cnt[d[l]];i++)printf("%d ",d[l]);
    for(int i=l+1;i<r;i++)for(int j=1;j<cnt[d[i]];j++)printf("%d ",d[i]);
    if(l!=r)for(int i=1;i<=cnt[d[r]];i++)printf("%d ",d[r]);
    for(int i=r-1;i>=l+1;i--)printf("%d ",d[i]);
    puts("");
}

int main(){
    read_and_parse();
    solve();
    return 0;
}

转载于:https://www.cnblogs.com/wzj-xhjbk/p/10781217.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值