zoukankan      html  css  js  c++  java
  • 【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
    ",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;
    }
    
  • 相关阅读:
    MyCLI :一个支持自动补全和语法高亮的 MySQL/MariaDB 客户端
    pathlib:优雅的路径处理库
    MySQL索引连环18问
    Mysql 百万级数据迁移实战笔记
    强大的Json解析工具 Jsonpath 实战教程
    JavaScript 中的 Var,Let 和 Const 有什么区别
    【前端安全】从需求分析开始,详解前端加密与验签实践
    vue3开发企业级生鲜系统项目
    mysql随笔
    shiro相关Filter
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10781217.html
Copyright © 2011-2022 走看看