solve the problem covering the interval in mathematic

The outputs:

5 3
1 3 8 5 11
The least length with m lines is:
7

The codes:

#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
int cover_interval(vector<int> v, int m);
int main()
{
    // Initialize the input parameters
    int n;
    cin >> n; // n represents the numbers of intervals in the input 
    int m; 
    cin >> m; // m represents the number of threads covering the intervals
    vector<int> v;
    int temp ; // variable to hold the temporary index of intervals you input from keyboard
    for (int i = 0; i < n; i++){
        cin >> temp;
        v.push_back(temp); 
    }
    //cout << v.size() << endl;
    //use cover_interval function to  calculate the result of the least length with m lines
    int value = 0;
    value = cover_interval(v, m);
    cout << "The least length with m lines is:" <<endl;
    cout << value << endl;
    return 0;
}
int cover_interval(vector<int> v, int m) 
{
    if(v.size() <= m){
        return v.size();
    }else{
        sort(v.begin(), v.end());
        vector<int> interval_v; // vector interval_v store the intervals between the elemetns in vector<int> v
        int length = v.size();
        for(int i = 1; i < length; i++){
            interval_v.push_back(v[i] - v[i-1] -1);
        }
        int result = v[v.size()-1] - v[0] +1;
        for(int i = 0; i < v.size()-m; i++){
            result -= interval_v[interval_v.size()-1-i];
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/120921547
今日推荐