2020 拼多多笔试题——输出优先级最高的N个数

AC

#include 

using namespace std;

void split(string &str, set &nums, char s = ',') {
   nums.clear();
   string tmp;
   istringstream is(str);
   while (getline(is, tmp, s)) {
      nums.insert(stoi(tmp));
   }
}

int main() {
   string str;
   getline(cin, str);
   set nums;
   long long len = str.size();
   int n = stoi(str.substr(str.find(';') + 1, len - 1));
   split(str, nums);
   set ou;
   set ji;
   for (set::iterator it = nums.begin(); it != nums.end(); it++) {
      if (((*it) & 1) == 0) {
         ou.insert(*it);
      }
      else {
         ji.insert(*it);
      }
   }
   long long oulen = ou.size();
   long long jilen = ji.size();
   long long count = 0;
   set::iterator it;
   if (n == 0) {
      return 0;
   }
   else if (n == 1) {
      it = ou.end();
      cout << *(it--) << ',';
      return 0;
   }
   else {
      if (oulen >= n) {
         for (it = ou.end(); it != ou.begin() && (count++ != (n - 1)); it--) {
            if (it == ou.end()) {
               it--;
            }
            cout << (*it) << ',';
         }
         cout << (*it);
         return 0;
      }
      else {
         for (it = ou.end(); it != ou.begin(); it--) {
            count++;
            if (it == ou.end()) {
               it--;
            }
            cout << (*it) << ',';
         }
         count++;
         cout << (*it) << ',';
         for (it = ji.end(); it != ji.begin() && (count++ != (n - 1)); it--) {
            if (it == ji.end()) {
               it--;
            }
            cout << (*it) << ',';
         }
         cout << (*it);
      }
   }
   return 0;
}

 

你可能感兴趣的:(秋招笔试题)