题目链接:http://abc043.contest.atcoder.jp/tasks/arc059_a
Time limit : 2sec / Memory limit : 256MB
Score : 200 points
Problem Statement
Evi has N integers a1,a2,..,aN. His objective is to have N equal integers by transforming some of them.
He may transform each integer at most once. Transforming an integer x into another integer y costs him (x−y)2 dollars. Even if 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≦100
- −100≦ai≦100
Input
The input is given from Standard Input in the following format:
N a1 a2 ... aN
Output
Print the minimum total cost to achieve Evi's objective.
Sample Input 1
2 4 8
Sample Output 1
8
Transforming the both into 6s will cost (4−6)2+(8−6)2=8 dollars, which is the minimum.
Sample Input 2
3 1 1 3
Sample Output 2
3
Transforming the all into 2s will cost (1−2)2+(1−2)2+(3−2)2=3 dollars. Note that Evi has to pay (1−2)2 dollar separately for transforming each of the two 1s.
Sample Input 3
3 4 2 5
Sample Output 3
5
Leaving the 4 as it is and transforming the 2 and the 5 into 4s will achieve the total cost of (2−4)2+(5−4)2=5 dollars, which is the minimum.
Sample Input 4
4 -100 -100 -100 -100
Sample Output 4
0
Without transforming anything, Evi's objective is already achieved. Thus, the necessary cost is 0.
题解:数据不大 枚举
1 #include <iostream> 2 #include <algorithm> 3 #include <cstring> 4 #include <cstdio> 5 #include <vector> 6 #include <cstdlib> 7 #include <iomanip> 8 #include <cmath> 9 #include <ctime> 10 #include <map> 11 #include <set> 12 #include <queue> 13 #include <stack> 14 using namespace std; 15 #define lowbit(x) (x&(-x)) 16 #define max(x,y) (x>y?x:y) 17 #define min(x,y) (x<y?x:y) 18 #define MAX 100000000000000000 19 #define MOD 1000000007 20 #define pi acos(-1.0) 21 #define ei exp(1) 22 #define PI 3.141592653589793238462 23 #define INF 0x3f3f3f3f3f 24 #define mem(a) (memset(a,0,sizeof(a))) 25 typedef long long ll; 26 ll gcd(ll a,ll b){ 27 return b?gcd(b,a%b):a; 28 } 29 bool cmp(int x,int y) 30 { 31 return x>y; 32 } 33 const int N=10005; 34 const int mod=1e9+7; 35 int a[101]; 36 int main() 37 { 38 std::ios::sync_with_stdio(false); 39 int n; 40 while(cin>>n){ 41 int s=0; 42 for(int i=0;i<n;i++) 43 cin>>a[i]; 44 sort(a,a+n); 45 if(a[0]==a[n-1]) cout<<s<<endl; 46 else{ 47 s=1234567; 48 int t=0,j; 49 for(int i=a[0];i<a[n-1];i++){ 50 t=0; 51 for(j=0;j<n;j++){ 52 t+=(i-a[j])*(i-a[j]); 53 } 54 if(t<s) s=t; 55 } 56 cout<<s<<endl; 57 } 58 } 59 return 0; 60 }