Codeforces R317 DIV1 B. Minimization
Chieh
posted @ 2015年8月23日 12:28
in NO Answer No Speak
, 206 阅读
/* Author:Chieh Because Of Coding */ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <vector> #include <map> #include <stack> #include <queue> #include <set> #define LL long long #define INF 1e9 #define EPS 1e-9 using namespace std; const int maxn=3*123456; int ai[maxn]; int n,k; bool cmp(int a,int b) { return a>b; } void init() { for(int i=1; i<=n; i++)scanf("%d",&ai[i]); sort(ai+1,ai+1+n,cmp); } LL dp[5678][5678]; void play() { if(n%k==0) { LL sum=0; int p=n/k; for(int i=1; i<=n; i+=p) { sum+=ai[i]-ai[i+p-1]; } printf("%I64d\n",sum); } else { int ys=n%k; int s1=ys; int v1=n/k+1; int s2=k-ys; int v2=n/k; for(int i=0; i<=k; i++) { for(int j=0; j<=k; j++) { dp[i][j]=1000000000000000000LL; } } dp[0][0]=0; for(int i=0;i<=s1;i++){ for(int j=0;j<=s2;j++){ int a1=i; int a2=j; int st=i*v1+j*v2+1; if(a1<s1){ dp[a1+1][a2]=min(dp[a1+1][a2],dp[a1][a2]+ai[st]-ai[st+v1-1]); } if(a2<s2){ dp[a1][a2+1]=min(dp[a1][a2+1],dp[a1][a2]+ai[st]-ai[st+v2-1]); } } } printf("%I64d\n",dp[s1][s2]); } } int main() { while(scanf("%d%d",&n,&k)!=EOF) { init(); play(); } // cout << "Hello world!" << endl; return 0; }