http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2074
题目描述
用i来表示x坐标轴上坐标为[i-1,i]的长度为1的区间,并给出n(1≤M≤200)个不同的整数,表示n个这样的区间。
现在要求画m条线段覆盖住所有的区间,
条件是:每条线段可以任意长,但是要求所画线段的长度之和最小,
并且线段的数目不超过N(1≤N≤50)。
输入
输入包括多组数据,每组数据的第一行表示点n,和所需线段数m,后面的n行表示点的坐标
输出
输出每组输出占一行表示线段的长度。
示例输入
5 3 1 3 5 8 11
示例输出
7
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
int n,m,a[300],b[300];
while(cin >> n>>m)
{
for(int i=0; i<n; i++)
cin>> a[i];
sort(a,a+n);
int j=0;
for(int i=1; i<n; i++)
if(a[i]-a[i-1]>1)
b[j++]=a[i]-a[i-1]-1;
sort(b,b+j);
int sum=0;
for(int i=j-1; i>=0&&j-1-i<m-1; i--)//i>=0考虑了n<m的情况
sum+=b[i];
cout << a[n-1]-a[0]+1-sum<<endl;
}
return 0;
}