ZeroJudge C635: Basic Sorting

There are several lines of test data. Each line contains 10 to 20 numbers separated by commas. Please 'sort the numbers separately at odd and even positions in the sequence', and output the results.

Sample Inputs/Outputs

Sample Input(s)Sample Output(s)
EOF input. Each line of test data contains 10 to 20 numbers separated by commas, N (1 ≤ N ≤ 100000).Sort the numbers at odd and even positions in the sequence separately, and output the results.
4806,39740,87462,16241,69980,93315,67864806,16241,6786,39740,69980,93315,87462

Thought Process

First, collect the entire input using a string. Then, split the string into numbers, and sequentially place the numbers at odd or even positions into separate arrays.

After sorting both arrays, run a for loop to output the data from both arrays alternately.

Sample Code-ZeroJudge C635: Basic Sorting

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int toint(const string& str) {
    if (str.length() == 1) return str[0] - '0';
    return stoi(str);
}

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    string str;
    while (cin >> str) {
        string tmp = "";
        vector<int>odd, even;
        int count = 1;
        for (int i = 0; i<str.length(); i++) {
            if (str[i] == ',' && !tmp.empty()) {
                if (count % 2 == 0) even.push_back(toint(tmp));
                else odd.push_back(toint(tmp));
                count++;
                tmp = "";
                continue;
            }
            tmp += str[i];
        }
        if (!tmp.empty()) {
            if (count % 2 == 0) even.push_back(toint(tmp));
            else odd.push_back(toint(tmp));
        }
        sort(odd.begin(), odd.end());
        sort(even.begin(), even.end());
        int o = 0, e = 0;
        for (int i = 0; i<count; i++) {
            if (i % 2 == 0) {
                cout << odd[o];
                o++;
            }
            else {
                cout << even[e];
                e++;
            }
            if (i != count-1) cout << ",";
        }
        cout << "\n";
    }
}

//ZeroJudge C635
//Dr. SeanXD

Comments