You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined . You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1.
Output the minimum possible value of error after k1 operations on array A and k2 operations on array B have been performed.
The first line contains three space-separated integers n (1 ≤ n ≤ 103), k1 and k2(0 ≤ k1 + k2 ≤ 103, k1 and k2 are non-negative) — size of arrays and number of operations to perform on A and B respectively.
Second line contains n space separated integers a1, a2, ..., an ( - 106 ≤ ai ≤ 106) — array A.
Third line contains n space separated integers b1, b2, ..., bn ( - 106 ≤ bi ≤ 106)— array B.
Output a single integer — the minimum possible value of after doing exactly k1operations on array A and exactly k2 operations on array B.
2 0 0 1 2 2 3
2
2 1 0 1 2 2 2
0
2 5 7 3 4 14 4
1
In the first sample case, we cannot perform any operations on A or B. Therefore the minimum possible error E = (1 - 2)2 + (2 - 3)2 = 2.
In the second sample case, we are required to perform exactly one operation on A. In order to minimize error, we increment the first element of A by 1. Now, A = [2, 2]. The error is now E = (2 - 2)2 + (2 - 2)2 = 0. This is the minimum possible error obtainable.
In the third sample case, we can increase the first element of A to 8, using the all of the 5moves available to us. Also, the first element of B can be reduced to 8 using the 6 of the 7available moves. Now A = [8, 4] and B = [8, 4]. The error is now E = (8 - 8)2 + (4 - 4)2 = 0, but we are still left with 1 move for array B. Increasing the second element of B to 5 using the left move, we get B = [8, 5] and E = (8 - 8)2 + (4 - 5)2 = 1.
原谅我水题也发博客,这道题的意思是给定两个数组,在给K1,K2个操作,分别对A,B数组操作,一个操作是对一个数➕1或者➖1,且一定要使K个操作用完,最后其对应的差的平方的和最小,并输出这个最小值。
这道题给我最大的启示是10的5次方以下的数据的题直接暴力都没问题,别想着优化,每多想十秒,别人可能就一血了。
首先,这个问题直接转化成|Ai-Bi|差值的最大值要最小,所以我用的是优先队列,(貌似杀鸡用了牛刀)。有两种情况,详情看代码。
#include<bits/stdc++.h>
using namespace std;
priority_queue <long long> q;
int main() {
long long n, k1, k2, a[10000], b[10000], c[10000];
while(cin >> n >> k1 >> k2) {
int sum = 0;
for(int i = 0; i < n; i++) {
cin >> a[i];
}
for(int i = 0; i < n; i++) {
cin >> b[i];
}
for(int i = 0; i < n; i++) {
c[i] = abs(a[i] - b[i]);
sum += c[i];
}
for(int i = 0; i < n; i++) {
q.push(c[i]);
}
int k = k1 + k2;
if(sum < k) {
if((k - sum) % 2 == 0) {
puts("0");
} else {
puts("1");
}
continue;
} else {
while(k > 0) {
long long temp = q.top();
temp--;
k--;
q.pop();
q.push(temp);
}
long long ans = 0;
while(!q.empty()) {
ans += q.top() * q.top();
q.pop();
}
cout << ans << endl;
}
}
}