백준 CPP 공부 2025.05.17
10814번 나이순 정렬
1. 문제
온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다.
이때, 회원들을 나이가 증가하는 순으로,
나이가 같으면 먼저 가입한 사람이 앞에 오는 순서로 정렬하는 프로그램을 작성하시오.
2. 입력
첫째 줄에 온라인 저지 회원의 수 N이 주어진다. (1 ≤ N ≤ 100,000)
둘째 줄부터 N개의 줄에는 각 회원의 나이와 이름이 공백으로 구분되어 주어진다.
나이는 1보다 크거나 같으며, 200보다 작거나 같은 정수이고,
이름은 알파벳 대소문자로 이루어져 있고, 길이가 100보다 작거나 같은 문자열이다.
입력은 가입한 순서로 주어진다.
3. 출력
첫째 줄부터 총 N개의 줄에 걸쳐 온라인 저지 회원을 나이 순,
나이가 같으면 가입한 순으로 한 줄에 한 명씩 나이와 이름을 공백으로 구분해 출력한다.
4. 문제 풀이
1) STD vector 와 구조체 활용
stable_sort의 경우
같은 값(키)을 가진 원소들의 상대적인 순서를 유지하면서 정렬하는 알고리즘으로서
해당 문제에 적합하며, 가입 시기를 따로 생각하지 않아도 된다.
>> 코드 1
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct Member {
int age;
int idx;
string name;
};
bool compare(const Member& a, const Member& b) {
return a.age < b.age;
}
int main() {
int n;
cin >> n;
vector<Member> members;
for (int i = 0; i < n; ++i) {
int age;
string name;
cin >> age >> name;
members.push_back({age, i, name});
}
stable_sort(members.begin(), members.end(), compare);
for (const auto& m : members) {
cout << m.age << " " << m.name << '\n';
}
return 0;
}
2) STD list 와 클래스 활용
listing 클래스를 생성해서 나이, 가입시기, 이름을 저장하고,
이를 list 연결리스트 구조를 이용하여 sort로 정렬하였다.
>>코드 2
#include <iostream>
#include <list>
#include <string>
using namespace std;
class listing {
int age;
int idx;
string name;
public:
listing(int age = 1, int idx = 1, string name = "KIM") {
this->age = age;
this->idx = idx;
this->name = name;
}
~listing() {}
int getage() const { return age; }
int getidx() const { return idx; }
string getname() const { return name; }
};
bool compare(const listing &A, const listing &B) {
if (A.getage() == B.getage()) return A.getidx() < B.getidx();
else return A.getage() < B.getage();
}
int main() {
int n;
cin >> n;
list<listing> OnlineJudge;
for (int i = 0; i < n; i++) {
int age;
string name;
cin >> age >> name;
OnlineJudge.push_back(listing(age, i, name));
}
OnlineJudge.sort(compare);
for (auto it = OnlineJudge.begin(); it != OnlineJudge.end(); it++) {
cout << it->getage() << " " << it->getname() << endl;
}
}
'백준 > 백준 C++' 카테고리의 다른 글
백준 C++ 1181번 단어 정렬 (Today I Learn 2025.05.16) (0) | 2025.05.19 |
---|---|
백준 C++ 10845번 큐 (Today I Learn 2025.05.14) (0) | 2025.05.14 |
백준 C++ 2798번 블랙잭 (Today I Learn 2025.03.14) (0) | 2025.03.15 |
백준 C++ 4153번 직각삼각형 (Today I Learn 2025.03.13) (0) | 2025.03.14 |