Official

E - アナグラム Editorial by QCFium


\(N\) の上限が \(5\) と小さいので、\(S\) を並び替えてできる最大 \(N!\) 個の文字列を全部試すことができます。
C++ では std::next_permutation 、python では itertools.permutations など、並び替えの全列挙をサポートする標準関数が存在する言語もあります。

解答例 (C++)

#include <algorithm>
#include <iostream>
#include <string>

int main() {
	scanf("%*d");
	std::string s;
	std::cin >> s;
	auto s_org = s;
	
	std::sort(s.begin(), s.end());
	
	do {
		if (s != s_org && s != std::string(s_org.rbegin(), s_org.rend())) {
			puts(s.c_str());
			return 0;
		}
	} while (std::next_permutation(s.begin(), s.end()));
	
	puts("None");
	
	return 0;
}

posted:
last update: