hihoCoder 1595 : Numbers

Description

You are given n constant integers c[1], c[2], ..., c[n] and an integer k. You are to assign values to 2k integer variables, x[1], x[2], ..., x[k], y[1], y[2], ..., y[k], such that,

(1) For each 1 ≤ i ≤ k, x[i] ≤ y[i] holds,

(2) For each 1 ≤ i ≤ n, exists at least one such j (1 ≤ j ≤ k) that x[j] ≤ c[i] ≤ y[j].

Please find the minimum value of S=(y[1]+y[2]+...+y[k])-(x[1]+x[2]+...+x[k]).

Input

First line contains two integers n, k. (1 ≤ n, k ≤ 100000)

Following n lines contain integers c[1], c[2], ..., c[n]. (-1000000000 ≤ c[i] ≤ 1000000000)

Output

Output the minimum value of integer S.

Sample Hint

x[1]=-5, y[1]=4,

x[2]=10, y[2]=10.
比赛中唯一让人感到美好的题目
按从小到大排序
定义一个区间大小为最大减最小
那么题目就是要把n个数分为k个区间,使和最小
贪心,一开始只分出1~n一个区间,后面将k-1个相邻差最大的值减去
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 int n,k,c[100001],d[100001];
 7 long long ans;
 8 bool cmp(int a,int b)
 9 {
10     return a>b;
11 }
12 int main()
13 {int i;
14     cin>>n>>k;
15     for (i=1;i<=n;i++)
16     {
17         scanf("%d",&c[i]);
18     }
19     sort(c+1,c+n+1);
20     ans=c[n]-c[1];
21     for (i=1;i<n;i++)
22     d[i]=c[i+1]-c[i];
23     sort(d+1,d+n,cmp);
24     for (i=1;i<=k-1;i++)
25     {
26         ans-=d[i];
27     }
28     cout<<ans;
29 }

 


posted @ 2017-10-01 21:26  Z-Y-Y-S  阅读(224)  评论(0编辑  收藏  举报