atcoder313C
313C
题目概述:给定序列A,可以任选两个数,使其中一个数加1,另一个数减1.可以通过任意次操作,问需要至少多少次操作,才能使A中最大数和最小数差值不超过1。
解题思路:将该题进行抽象转化:1.我们需要将A序列转化为B序列,sumB=sumA。
操作次数为:
2. B序列的最大值和最小值的差值不超过1(最多只有两种数),且该序列需使上述式子的值尽可能小。使用A的平均值p作为B序列的项(从整体上看,A的平均数与每项差值的绝对值和较小),后r项等于p+1(r=sumA % n)(不太清楚为什么是p+1)
点击查看代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <set>
#include <vector>
#include <map>
#include <set>
using namespace std;
typedef long long LL;
typedef pair<int,int>PII;
const int N = 200010;
vector<int>v[N];
int ans;
int a[N];
int n;
int main(){
cin >> n;
LL sum = 0;
for(int i = 0; i < n; i ++){
cin >> a[i];
sum = (LL)sum + a[i];
}
sort(a,a + n);
vector<int>b(n,sum / n);
for(int i = 0; i < sum % n; i ++){
b[n - 1 - i]++;
}
LL res = 0;
for(int i = 0; i < n; i ++){
res = (LL)res + abs(a[i] - b[i]);
}
cout << res / 2 << endl;
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库