跳到正文

题解

CF1661C题解

glorious_dream约 3 分钟
原文
文章信息与版本

文章信息

发布
2022年5月5日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 3 分钟
获赞
4
题目
CF1661C

版本

  1. v1当前

题意描述:

给定 nn 棵树的高度,奇数次操作让树长 11 米,偶数次操作让树长 22 米,求最少步数使树高相同。

算法分析:

我们发现,只有两种情况,奇数次和偶数次。那么,可以贪心来考虑。

可以发现,设定一个目标高度,显然每棵树有两种情况,要么差是偶数,要么差是奇数。

这时,偶数我们就可以在偶数次操作,奇数可以在奇数次操作。但最后肯定会剩余某些树,要么是全差奇数次,要么是全差偶数次。

所以说,如果需要 +2+2 的次数多,就尽可能把 +2+2 分给 +1+1。

我们可以 33 个 +2+2 为一组,为什么呢?可以发现,等于 22 个 +1+1 和 22 个 +2+2,这时再去贪心求解,答案就出来了。

总代码:

C++
#include<bits/stdc++.h>
#define re register
#define int long long
using namespace std;
inline int read(){
	int x=0,f=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch == '-') f=-1 ; ch=getchar();}
	while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48) ; ch=getchar();}
	return x*f;
}
inline void print(int x){
	if(x/10) print(x/10);
	putchar(x%10+'0');
}
const int M = 3e5+10;
int t,n;
int a[M];
inline int work(int maxn){
	int cnt1=0,cnt2=0;
	for(re int i(1) ; i<=n ; ++i){
		cnt1 += (maxn-a[i])%2;
		cnt2 += (maxn-a[i])/2; //贪心求解
	}
	int tmp = cnt2 - cnt1;
	if(tmp >= 2) cnt1+=(tmp+1)/3*2,cnt2-=(tmp+1)/3;
	if(cnt1 > cnt2) return cnt1*2-1;
	else return cnt2*2;
}
signed main(){
	t=read();
	while(t--){
		int maxn=0;
		n=read();
		for(re int i(1) ; i<=n ; ++i){
			a[i] = read();
			maxn = max(maxn,a[i]);
		}
		printf("%lld\n",min(work(maxn),work(maxn+1)));
      //解释一下为什么要两次
      //要么是奇数多一个,要么就是相同,求最小的,肯定是最优解
	}
	return 0;
}
原文