区间覆盖问题java

区间覆盖问题
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem 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
Sample Output
7
Hint
注意:题目数据已于2018.4.16更新
Source

import java.util.*;

class myclass {
    int arr[];
    int n;
    int b[];
    int m;

    myclass(int a[], int n, int m) {
        this.arr = a;
        this.n = n;
        b = new int[205];
        this.m = m;
    }

    void sort(int a[], int n) {
        int i, j;
        int t;
        for (i = 0; i < n - 1; i++) {
            for (j = 0; j < n - i - 1; j++) {
                if (a[j] > a[j + 1]) {
                    t = a[j + 1];
                    a[j + 1] = a[j];
                    a[j] = t;
                }
            }
        }
    }

    void main() {
        int s, e;
        sort(this.arr, this.n);
        s = arr[0];
        e = arr[this.n - 1];
        for (int i = 0; i < this.n - 1; i++) {
            b[i] = arr[i + 1] - arr[i] - 1;
            // System.out.println(b[i]);
        }
        sort(b, n - 1);
        int i;
        i = n - 2;
        int l = arr[n - 1] - arr[0] + 1;
        m--;
        while (m > 0) {
            l -= b[i--];
            m--;
        }
        System.out.println(l);
    }
}

class Main {
    public static void main(String[] args) {

        Scanner ss = new Scanner(System.in);
        int n, m;
        final int mm = 205;
        while (ss.hasNextInt()) {
            n = ss.nextInt();
            m = ss.nextInt();
            int i, j;
            int s, e;
            int a[] = new int[mm];
            int b[] = new int[mm];
            for (i = 0; i < n; i++)
                a[i] = ss.nextInt();
            if (m == n) {
                System.out.println(m);
            } else {
                myclass per = new myclass(a, n, m);
                per.main();
            }
        }

        ss.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值