题目描述:
C - いっしょ / Be Together
Time Limit: 2 sec / Memory Limit: 256 MB
Score : 200200 points
Problem Statement
Evi has NN integers a1,a2,..,aNa1,a2,..,aN. His objective is to have NN equal integers by transforming some of them.
He may transform each integer at most once. Transforming an integer xx into another integer yy costs him (x−y)2(x−y)2 dollars. Even if ai=aj(i≠j)ai=aj(i≠j), he has to pay the cost separately for transforming each of them (See Sample 2).
Find the minimum total cost to achieve his objective.
Constraints
- 1≦N≦1001≦N≦100
- −100≦ai≦100−100≦ai≦100
Input
The input is given from Standard Input in the following format:
NN a1a1 a2a2 ... aNaN
Output
Print the minimum total cost to achieve Evi's objective.
Sample Input 1 Copy
Copy
2 4 8
Sample Output 1 Copy
Copy
8
Transforming the both into 66s will cost (4−6)2+(8−6)2=8(4−6)2+(8−6)2=8 dollars, which is the minimum.
Sample Input 2 Copy
Copy
3 1 1 3
Sample Output 2 Copy
Copy
3
Transforming the all into 22s will cost (1−2)2+(1−2)2+(3−2)2=3(1−2)2+(1−2)2+(3−2)2=3 dollars. Note that Evi has to pay (1−2)2(1−2)2 dollar separately for transforming each of the two 11s.
Sample Input 3 Copy
Copy
3 4 2 5
Sample Output 3 Copy
Copy
5
Leaving the 44 as it is and transforming the 22 and the 55 into 44s will achieve the total cost of (2−4)2+(5−4)2=5(2−4)2+(5−4)2=5 dollars, which is the minimum.
Sample Input 4 Copy
Copy
4 -100 -100 -100 -100
Sample Output 4 Copy
Copy
0
Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 00.
思路:
首先这题很定可以暴力,但是之前做过好多类似的题目,有的是用中位数,有的平均数,
(本题平均数两边取值即可?why?),这种题目要总结一下。
代码实现:
没有分清楚该用什么,所以这里直接中位数+平均数然后4个答案中选择了最优的。
#include<bits/stdc++.h>
#define LL long long
#define INF 0x3f3f3f3f
#define io ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
const int N=2e5+100;
using namespace std;
int a[N];
int main()
{
io;
int n;
while(cin>>n)
{
int sum=0;
for(int i=1;i<=n;++i)cin>>a[i],sum+=a[i];
int ave=sum/n;
sort(a+1,a+1+n);
int ans1=0;
int ans2=0;
int ans=INF;
if(n&1)
{
for(int i=1;i<=n;++i)ans1+=(a[n/2+1]-a[i])*(a[n/2+1]-a[i]);
ans=min(ans,ans1);
}
else
{
for(int i=1;i<=n;++i)ans1+=(a[n/2+1]-a[i])*(a[n/2+1]-a[i]);
for(int i=1;i<=n;++i)ans2+=(a[n/2]-a[i])*(a[n/2]-a[i]);
ans=min(ans1,ans2);
}
for(int i=1;i<=n;i++)
{
ans1=0;
ans2=0;
for(int i=1;i<=n;++i)ans1+=(ave-a[i])*(ave-a[i]);
for(int i=1;i<=n;++i)ans2+=(ave+1-a[i])*(ave+1-a[i]);
ans=min(ans,ans1);
ans=min(ans,ans2);
}
cout<<ans<<endl;
}
return 0;
}
The end;