반응형
[문제 풀이]
1. 각각의 조건에 맞는 조건 작성
2. 조건에 맞게 정렬
[코드]
- A와 B의 길이가 다르면, 짧은 것이 먼저 온다.
bool compare(string a, string b){
int a_len = a.length();
int b_len = b.length();
if(a_len != b_len){
return a_len < b_len;
}
}
- 만약 서로 길이가 같다면, A의 모든 자리수의 합과 B의 모든 자리수의 합을 비교해서 작은 합을 가지는 것이 먼저 온다. (숫자인 것만 더한다)
bool compare(string a, string b){
int a_tmp = 0;
int b_tmp = 0;
for(int i=0; i<a_len; i++){
if(a[i] - '0' >= 0 && a[i] - '0' <= 9){
a_tmp += a[i] - '0';
}
if(b[i] - '0' >= 0 && b[i] - '0' <= 9){
b_tmp += b[i] - '0';
}
}
if(a_tmp != b_tmp) {
return a_tmp < b_tmp;
}
}
- 만약 1, 2번 둘 조건으로도 비교할 수 없으면, 사전순으로 비교한다. 숫자가 알파벳보다 사전순으로 작다.
bool compare(string a, string b){
return a<b;
}
[전체 코드]
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
bool compare(string a, string b){
int a_len = a.length();
int b_len = b.length();
if(a_len != b_len){
return a_len < b_len;
}
int a_tmp = 0;
int b_tmp = 0;
for(int i=0; i<a_len; i++){
if(a[i] - '0' >= 0 && a[i] - '0' <= 9){
a_tmp += a[i] - '0';
}
if(b[i] - '0' >= 0 && b[i] - '0' <= 9){
b_tmp += b[i] - '0';
}
}
if(a_tmp != b_tmp) {
return a_tmp < b_tmp;
}
return a<b;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N;
string s[51];
cin>>N;
for(int i=0; i<N; i++){
cin>>s[i];
}
sort(s, s+N, compare);
for(int i=0; i<N; i++){
cout<<s[i]<<"\n";
}
return 0;
}
https://www.acmicpc.net/problem/1431
반응형
'Algorithm > Baekjoon' 카테고리의 다른 글
[ 백준 10994 ] 별 찍기 - 19 (C++) (0) | 2025.02.23 |
---|---|
[ 백준 2503 ] 숫자 야구 (C++) (0) | 2025.02.15 |
[ 백준 1388 ] 바닥 장식 (JAVA) (0) | 2025.01.31 |
[ 백준 12789 ] 도키도키 간식드리미 (C++) (0) | 2025.01.26 |
[ 백준 17266 ] 어두운 굴다리 (JAVA) (1) | 2025.01.13 |