Official
A - Distinct Strings Editorial by penguinman
以下のような場合分けが可能です。
- \(S\) に含まれる \(3\) 文字が全て同じである場合、答えは明らかに \(1\) 通りである。
- そうでなく、\(S\) に含まれる \(3\) 文字が互いに異なる場合、答えは \(3!=6\) 通りである。
- 上記 \(2\) つのどれでもない場合、\(S\) は等しい \(2\) 文字とそれとは異なる \(1\) 文字によって構成されており、故に答えは \(3\) 通りである。
これをこのままコードに移すと AC となります。
実装例 (C++)
#include<bits/stdc++.h>
using namespace std;
int main(){
string S; cin >> S;
int ans = 3;
if(S[0]==S[1] && S[1]==S[2]) ans = 1;
else if(S[0]!=S[1] && S[1]!=S[2] && S[2]!=S[0]) ans = 6;
cout << ans << endl;
}
実装例 (Python)
S = input()
ans = 3
if S[0] == S[1] and S[1] == S[2]:
ans = 1
elif S[0] != S[1] and S[1] != S[2] and S[0] != S[2]:
ans = 6
print(ans)
なお、順列全探索と呼ばれる手法を用いることで場合分けをすることなく解くことも可能です。
実装例 (C++)
#include<bits/stdc++.h>
using namespace std;
int main(){
string S; cin >> S;
sort(S.begin(),S.end());
set<string> s;
do{
s.insert(S);
}while(next_permutation(S.begin(),S.end()));
cout << s.size() << endl;
}
posted:
last update: