Interval coverage problem java

Interval coverage problem
Time Limit: 1000 ms Memory Limit: 65536 KiB
Submit Statistic
Problem Description
Use i to represent the interval of length 1 with coordinates [i-1, i] on the x-axis, and give n (1≤n≤ 200) distinct integers representing n such intervals.
Now it is required to draw m line segments to cover all the intervals, the
condition is: each line segment can be arbitrarily long, but the sum of the lengths of the drawn line segments is required to be the smallest,
and the number of line segments does not exceed m (1≤m≤50).

Input
input includes multiple sets of data, the first line of each set of data represents the number of intervals n and the number of required line segments m, and the second line represents the coordinates of n points.
Output
Each group of outputs occupies one line, and outputs the minimum length sum of m line segments.
Sample Input
5 3
1 3 8 5 11
Sample Output
7
Hint Note: The title data has been updated Source
on 2018.4.16

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();
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325989155&siteId=291194637
Recommended