HDU 5734 - Acperience
题意:
给出集合W(w1,w2,w3...,wn) 找到 x 使得 sqrt( (w1-x)^2 + (w2-x)^2 + .... + (wn-x)^2 ) 最小,求这个最小值;
分析:
(w1-x)^2 + (w2-x)^2 + .... + (wn-x)^2
= n * x^2 + 2*(w1+w2+...+wn) * x + (w1^2+w2^2+...+wn^2)
则
a = n
b = 2 * (w1 + w2 + ... + wn)
c = (w1^2 + w2^2 + ... + wn^2)
Min^2 = (4ac - b^2) / (4a)
1 #include <iostream> 2 using namespace std; 3 long long s[100005]; 4 int t,n; 5 long long GCD(long long a,long long b) 6 { 7 return b==0? a: GCD(b,a%b); 8 } 9 int main() 10 { 11 scanf("%d",&t); 12 while(t--) 13 { 14 scanf("%d",&n); 15 long long b=0,a=n,c=0,d=0,tu,td; 16 for(int i=1;i<=n;i++) 17 { 18 scanf("%lld",&s[i]); 19 if(s[i]<0) s[i]=-s[i]; 20 b+=s[i]; 21 c+=s[i]*s[i]; 22 } 23 tu=(a*c-b*b); 24 td=a; 25 if(tu==0) 26 { 27 puts("0/1"); continue; 28 } 29 long long p=GCD(tu,td); 30 tu/=p; 31 td/=p; 32 printf("%lld/%lld\n",tu,td); 33 } 34 }
我自倾杯,君且随意