나도 공부한다/알고리즘
[백준] 1431. 시리얼 번호 (C++)
꾸빵이
2023. 5. 11. 18:14
Level
Silver3
Idea
두번째 조건에서 숫자의 합을 저장하기 위해 map을 사용했고 정렬을 위해 vector을 사용했다. 그런데 생각해보니 1번 조건을 검사하지 않았는데도 미리 숫자의 합을 계산해두는건 좋은 방법이 아닌 것 같다. 굳이 맵을 사용하지 않아도 충분히 풀 수 있는 문제였다. 다른 사람들의 풀이를 봤는데 대부분 문자열 배열로 푸는것 같아서 나도 문자열 배열 버전으로 한번 더 풀었다. 사실 벡터나 문자열 배열이나 비슷하지만... 첫번째 코드는 내가 처음에 짠 코드고, 두번째 코드는 문자열 배열로 푼 코드다.
Code
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
map<string, int>mp;
bool cmp(pair<string, int>a, pair<string, int>b) {
if (a.first.size() != b.first.size()) {
return a.first.size() < b.first.size();
}
else {
if (mp[a.first] != mp[b.first]) {
return mp[a.first] < mp[b.first];
}
else {
return a.first < b.first;
}
}
}
int main() {
int n = 0;
int add = 0;
string st;
cin >> n;
for (int i = 0; i < n; i++) {
add = 0;
cin >> st;
for (int j = 0; j < st.size(); j++) {
if (st[j] >= '0' && st[j] <= '9') {
add += st[j] - '0';
}
}
mp.insert({ st,add });
}
vector<pair<string, int>>v(mp.begin(), mp.end());
sort(v.begin(), v.end(), cmp);
for (auto a : v) {
cout << a.first << endl;
}
}
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(string a, string b) {
if (a.size() != b.size()) {
return a.size() < b.size();
}
else {
int result_a = 0;
int result_b = 0;
for (int i = 0; i < a.size(); i++) {
if (a[i] >= '0' && a[i] <= '9') {
result_a += a[i] - '0';
}
if (b[i] >= '0' && b[i] <= '9') {
result_b += b[i] - '0';
}
}
if (result_a != result_b) {
return result_a < result_b;
}
else {
return a < b;
}
}
}
int main() {
string st_arr[50];
int n = 0;
string st;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> st_arr[i];
}
sort(st_arr, st_arr+n, cmp);
for (int i = 0; i < n; i++) {
cout << st_arr[i] << endl;
}
}