cses

My solution for the coding challenges of cses.fi
git clone https://git.tronto.net/cses
Download | Log | Files | Refs | README

string_reorder_1743.cpp (796B)


      1 #include <algorithm>
      2 #include <array>
      3 #include <iostream>
      4 #include <iterator>
      5 #include <sstream>
      6 #include <string>
      7 
      8 int main() {
      9 	std::array<size_t, 26> a{};
     10 	std::string s;
     11 	std::cin >> s;
     12 	for (auto c : s) a[c-'A']++;
     13 
     14 	size_t i{0}, j{1}, tot{s.size()}, c{99};
     15 	std::stringstream ss{};
     16 	while (*std::max_element(a.begin(), a.end()) <= tot / 2) {
     17 		while (a[i] == 0) i++;
     18 		while (a[j] == 0 || j <= i) j++;
     19 		c = i == c ? j : i;
     20 		ss << (char)('A' + c);
     21 		a[c]--;
     22 		tot--;
     23 	}
     24 
     25 	j = std::distance(a.begin(), std::max_element(a.begin(), a.end()));
     26 	while (a[j] > 1) {
     27 		if (tot == a[j]) {
     28 			std::cout << "-1\n";
     29 			return 0;
     30 		}
     31 		while (a[i] == 0 || i == j) i++;
     32 		ss << (char)('A' + j) << (char)('A' + i);
     33 		a[i]--;
     34 		a[j]--;
     35 		tot -= 2;
     36 	}
     37 	std::cout << ss.str() << (char)('A' + j) << "\n";
     38 }