您的位置:首页 > 其它

区间覆盖问题

2017-04-09 21:01 295 查看
Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

用i来表示x坐标轴上坐标为[i-1,i]的长度为1的区间,并给出n(1≤n≤200)个不同的整数,表示n个这样的区间。

现在要求画m条线段覆盖住所有的区间,

条件是:每条线段可以任意长,但是要求所画线段的长度之和最小,

并且线段的数目不超过m(1≤m≤50)。

Input

输入包括多组数据,每组数据的第一行表示点n,和所需线段数m,后面的n行表示点的坐标

Output

输出每组输出占一行表示线段的长度。

Example Input

5 3

1 3 8 5 11

Example Output

7

解析

只要将最长长度求出来,然后求出每两个区间距离,最后用total减去b-1个最大的两个区间的距离。

代码实现:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(int a[], int n)//冒泡排序算法降序
{
int i, j, temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]<a[j+1])
{
temp = a[j], a[j] = a[j+1], a[j+1] = temp;
}
}
}
}
int main()
{
int a, b, i;
int p[205];//记录开始的覆盖区域
int d[205];//记录相邻覆盖区域之间的距离
while(~scanf("%d %d", &a, &b))//区间点,线段数
{
for(i=0;i<a;i++)
scanf("%d", &p[i]);//记录覆盖的区域
sort(p, a);//排序
for(i=0;i<a-1;i++)
d[i] = p[i] - p[i+1] - 1;//记录相邻覆盖区域的距离
sort(d, a-1);//按照距离大小排序
if(b>=a)//如果所画线段数大于区间点
printf("%d\n", a);//只用a条
else
{
int nline = 1;//线段条数
int total = p[0] - p[a-1] + 1;//记录线段的长度
int devide = 0;
while(nline<b&&d[devide]>0)
{
nline++;
total -= d[devide];//用总共的线段长度减去最大的b-1的距离
devide++;
}
printf("%d\n", total);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: