1431번:시리얼 번호
알파벳 대문자와 0~9의 숫자로 이루어진 문자열을 세가지 규칙에 따라 정렬하는 문제이다.
- 문자열의 길이
- 문자열속 숫자들의 총합
- 사전순
이 세가지 규칙에 따라 오름차순으로 정렬한다.
#include <bits/stdc++.h>
#define fastio cin.tie(0)->sync_with_stdio(0)
using namespace std;
vector<string> vs;
int sumNum(string s){
int ret = 0;
for (int i = 0; i < s.length();i++){
if(isdigit(s[i]))
ret += s[i] - '0';
}
return ret;
}
struct Cmp{
bool operator() (const string& a,const string& b) const{
if(a.size()!=b.size())
return a.size() < b.size();
else{
if(sumNum(a)!=sumNum(b))
return sumNum(a)< sumNum(b);
else
return a < b;
}
}
};
void input(){
int n;
cin >> n;
string s;
while(n--){
cin >> s;
vs.push_back(s);
}
return;
}
void output(){
for (auto &i : vs){
cout << i << '\n';
}
return;
}
void solution(){
input();
sort(vs.begin(),vs.end(),Cmp());
output();
}
int main() {
fastio;
solution();
}
Functor를 사용해 구조체 Cmp에서 ()연산자를 오버라이딩했다.
cmp 함수에서는 irreflexivity와 asymmetry를 만족시키기 위해 <= 연산자가 아닌 < 연산자로 return했다.