D - 区间覆盖问题
Description
用i来表示x坐标轴上坐标为[i-1,i]的长度为1的区间,并给出n(1≤n≤200)个不同的整数,表示n个这样的区间。
现在要求画m条线段覆盖住所有的区间,
条件是:每条线段可以任意长,但是要求所画线段的长度之和最小,
并且线段的数目不超过m(1≤m≤50)。
Input
输入包括多组数据,每组数据的第一行表示区间个数n和所需线段数m,第二行表示n个点的坐标。
Output
每组输出占一行,输出m条线段的最小长度和。
Sample
Input
5 3
1 3 8 5 11
Output
7
Hint
/*************************************************************************************/
思路:用pos数组记录每个区间的位置,并降序排列(便于求出之间的距离),并对距离排序,在最大距离处断开,得以求得覆盖所需的最小长度。
#include <stdio.h>
#include <string.h>
void sort(int a[],int n)//定一个降序函数
{
int i,j,t;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]<a[j+1])
{
t=a[j+1];
a[j+1]=a[j];
a[j]=t;
}
}
}
}
int main()
{
int m,n,i;
while(~scanf("%d %d",&n,&m))
{
int pos[201];
for(i=0;i<n;i++)
scanf("%d",&pos[i]);//记录区间的位置
int dis[201]={0};
sort(pos,n);
for(i=0;i<n-1;i++)
dis[i]=pos[i]-pos[i+1]-1;//记录每个区间的距离
sort(dis,n-1);//对距离进行降序
if(n>m)
{
int line=0;//记录所需线段个数
int tl=pos[0]-pos[n-1]+1;//求区间原长
int lar=0;
while(line<=m&&dis[lar]>0)
{
line++;
tl=tl-dis[lar];
lar++;
}
printf("%d\n",tl);
}
else printf("%d\n",n);
}
return 0;
}