题目来源:码蹄集
题目描述:
B站老师思路讲解链接:https://www.bilibili.com/video/BV1cx4y1N7j9/?t=3937.3&vd_source=3ae2a916df1bc5c1114c2bf3e95a2118
Python代码实现:
import time
from typing import List, Tuple
from collections import deque, Counter
from queue import PriorityQueue
import math
from functools import lru_cache
import random
import copy
import sys
sys.setrecursionlimit(99999999)
def main():
a, b = map(int, input().split())
arr = list(map(int, input().split()))
arr.sort()
tot = sum(arr)
tot -= a
cnt = b
ans = []
for v in arr:
avg = tot // cnt
x = tot % cnt
if v <= avg:
ans.append(v)
tot -= v
else:
if x > 0:
ans.append(avg + 1)
tot -= (avg + 1)
else:
ans.append(avg)
tot -= avg
cnt -= 1
val = 0
for v in ans:
val += v ** 2
print(val)
if __name__ == '__main__':
main();
参考链接:https://blog.51cto.com/u_15745546/5950611
C++代码实现:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
vector<int> arr(b);
for(int i=0; i<b; i++) {
cin >> arr[i];
}
sort(arr.begin(), arr.end());
int tot = 0;
for(int i=0; i<b; i++) {
tot += arr[i];
}
tot -= a;
int cnt = b;
vector<int> ans;
for(int i=0; i<b; i++) {
int avg = tot / cnt;
int x = tot % cnt;
if(arr[i] <= avg) {
ans.push_back(arr[i]);
tot -= arr[i];
}
else {
if(x > 0) {
ans.push_back(avg + 1);
tot -= (avg + 1);
x--;
}
else {
ans.push_back(avg);
tot -= avg;
}
}
cnt--;
}
int val = 0;
for(int i=0; i<b; i++) {
val += ans[i] * ans[i];
}
cout << val << endl;
return 0;
}
Java代码实现:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
List<Integer> arr = new ArrayList<>();
for(int i=0; i<b; i++) {
arr.add(sc.nextInt());
}
Collections.sort(arr);
int tot = 0;
for(int i=0; i<b; i++) {
tot += arr.get(i);
}
tot -= a;
int cnt = b;
List<Integer> ans = new ArrayList<>();
for(int i=0; i<b; i++) {
int avg = tot / cnt;
int x = tot % cnt;
if(arr.get(i) <= avg) {
ans.add(arr.get(i));
tot -= arr.get(i);
}
else {
if(x > 0) {
ans.add(avg + 1);
tot -= (avg + 1);
x--;
}
else {
ans.add(avg);
tot -= avg;
}
}
cnt--;
}
int val = 0;
for(int i=0; i<b; i++) {
val += ans.get(i) * ans.get(i);
}
System.out.println(val);
}
}