[SDUT](2074)区间覆盖问题 ---贪心

区间覆盖问题

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

 每组输出占一行,输出m条线段的最小长度和。

Example Input

5 3
1 3 8 5 11

Example Output

7

解题新知:

思路:贪心的思想,先把n的点的坐标排序,然后找m-1个两区间较长的距离,求出从起点即x[0]-1,到终点x[n-1]的总距离sum,用sum减去m-1个两区间较长的距离即可。

AC代码:
#include<iostream>
#include<algorithm>
using namespace std;
int x[500];
int a[500];
int n,m;
int main()
{
    while(cin>>n>>m)
    {
        for(int i=0;i<n;i++)
            cin>>x[i];
        sort(x,x+n);
        int sum=x[n-1]-(x[0]-1);
        int nn=n-1;
        for(int i=0;i<nn;i++)
        {
            a[i]=(x[i+1]-1)-x[i];
        }
        sort(a,a+nn);
        for(int i=0;i<m-1;i++)
            sum=sum-a[nn-1-i];
        cout<<sum<<endl;
    }
    return 0;
}


posted @ 2017-08-30 19:22  WangMeow  阅读(320)  评论(0编辑  收藏  举报