Luogu P2503 [HAOI2006]均分数据 题解

2022-09-19 08:32:39 浏览数 (2)

Link

题目传送门

题面

n个数字a_1,a_2,a_3dots a_n把他们分成m组,使得均方差最小。均方差公式如下: sigma = sqrt{frac 1n sumlimits_{i=1}^n(overline x – x_i)^2},overline x = frac 1n sumlimits_{i=1}^n x_i

思路

显然如果告诉你这n个数字固定的排列顺序就一定可以贪心求出最小值:将当前的数加入到最小的组中。 所以只需要randomtext{_} shuffle即可。

Code

代码语言:javascript复制
#include<algorithm>
#include<bitset>
#include<complex>
#include<deque>
#include<exception>
#include<fstream>
#include<functional>
#include<iomanip>
#include<ios>
#include<iosfwd>
#include<iostream>
#include<istream>
#include<iterator>
#include<limits>
#include<list>
#include<locale>
#include<map>
#include<memory>
#include<new>
#include<numeric>
#include<ostream>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<stdexcept>
#include<streambuf>
#include<string>
#include<typeinfo>
#include<utility>
#include<valarray>
#include<vector>
#include<cctype>
#include<cerrno>
#include<cfloat>
#include<ciso646>
#include<climits>
#include<clocale>
#include<cmath>
#include<csetjmp>
#include<csignal>
#include<cstdarg>
#include<cstddef>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
using namespace std;

#define re register
#define LD double
#define Temperature 500000
//#define int long long 

class Quick_Input_Output{
    private:
        static const int S=1<<21;
        #define tc() (A==B&&(B=(A=Rd) fread(Rd,1,S,stdin),A==B)?EOF:*A  )
        char Rd[S],*A,*B;
        #define pc putchar
    public:
        #undef gc
        #define gc getchar 
        inline int read(){
            int res=0,f=1;char ch=gc();
            while(ch<'0'ch>'9'){if(ch=='-') f=-1;ch=gc();}
            while(ch>='0'&&ch<='9') res=res*10 ch-'0',ch=gc();
            return res*f;
        }
        inline void write(int x){
            if(x<0) pc('-'),x=-x;
            if(x<10) pc(x '0');
            else write(x/10),pc(x '0');
        }
        #undef gc
        #undef pc
}I;
#define File freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);

int n,m,a[25],b[25];
LD sum,ans=20000000.0,s;
class Solve{
    public:
        inline void solve(){
            memset(b,0,sizeof(b));
            for(int i=1;i<=n;i  ){
                re int j=1;
                for(int k=1;k<=m;k  ){
                    if(b[k]<b[j]) j=k;
                }
                b[j] =a[i];
            }
            s=0.0;
            for(int i=1;i<=m;i  ) s =((LD)b[i]-sum)*(((LD)b[i]-sum));
            s/=(LD)m;
            ans=min(ans,s);
        }
        inline void init(){
            n=I.read();m=I.read();
            for(int i=1;i<=n;i  ) a[i]=I.read(),sum =(LD)a[i];
            sum/=(LD)m;
            for(int i=1;i<=Temperature;i  ){
                random_shuffle(a 1,a n 1);
                solve();
            }
            printf("%.2lfn",sqrt(ans));
        }
}S;
signed main(){
//  File
    S.init();
    return 0;
}
/*
6 3
1 2 3 4 5 6
*/ 

0 人点赞