Posted on

Description

Submission

  • Calculate the distance between each space station, half is the max distance in between
  • Special cases: the space stations in the beginning and at the end
#include <bits/stdc++.h>

using namespace std;

vector<string> split_string(string);

// Complete the flatlandSpaceStations function below.
int flatlandSpaceStations(int n, vector<int> c) {
    if(n == c.size()) return 0;
    if(n == 1) return max(c[0], n - c[0]);

    sort(c.begin(), c.end());

    int m = 0;

    for(auto iter1 = c.begin(), iter2 = next(iter1); 
            iter2 != c.end(); 
            advance(iter1, 1), advance(iter2, 1)) {
        if(*iter2 - *iter1 > m) {
            m = *iter2 - *iter1;
        }
    }
    m = m / 2;
    m = max(m, *c.begin());
    m = max(m, n - 1 - *prev(c.end()));
    return m;
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string nm_temp;
    getline(cin, nm_temp);

    vector<string> nm = split_string(nm_temp);

    int n = stoi(nm[0]);

    int m = stoi(nm[1]);

    string c_temp_temp;
    getline(cin, c_temp_temp);

    vector<string> c_temp = split_string(c_temp_temp);

    vector<int> c(m);

    for (int i = 0; i < m; i++) {
        int c_item = stoi(c_temp[i]);

        c[i] = c_item;
    }

    int result = flatlandSpaceStations(n, c);

    fout << result << "\n";

    fout.close();

    return 0;
}

vector<string> split_string(string input_string) {
    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
        return x == y and x == ' ';
    });

    input_string.erase(new_end, input_string.end());

    while (input_string[input_string.length() - 1] == ' ') {
        input_string.pop_back();
    }

    vector<string> splits;
    char delimiter = ' ';

    size_t i = 0;
    size_t pos = input_string.find(delimiter);

    while (pos != string::npos) {
        splits.push_back(input_string.substr(i, pos - i));

        i = pos + 1;
        pos = input_string.find(delimiter, i);
    }

    splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

    return splits;
}

Leave a Reply

Your email address will not be published. Required fields are marked *