백준 문제 풀이 & C++ 공부
백준 10814번 C++
daisy0461
2021. 7. 7. 21:53
이 문제를 완벽하게 이해하고 풀기 위해서
vector cotainer, pair, sort, stable_sort를 공부하였습니다.
pair를 제외하고는 다 제 블로그 안에 글들이 있으니 혹시 잘 모르신다면 한번 보시고
문제를 푸시는 걸 추천드립니다.
https://www.acmicpc.net/problem/10814
10814번: 나이순 정렬
온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한 사람이 앞에 오는 순서로 정렬하는 프로그램을
www.acmicpc.net
이 문제에서 중요한 사항중에 하나는 sort와 stable_sort의 차이점을 아는 것이 중요했던 것 같습니다.
불안정정렬을 사용할 경우
나이가 같다면 가입한 순으로 한 줄에 한 명씩 나이와 이름을 출력하라는 것이었습니다.
그렇다면 sort를 사용할 경우 가입한 순으로 나오지 않을 수 있기 때문에
stable_sort를 사용해야합니다.
처음으로 vector와 pair, stable_sort를 사용하며 편리하다는 생각과 빨리 익숙해져야겠다는 생각도 하였습니다.
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<string.h>
#include<utility>
#include<algorithm>
#include<vector>
using namespace std;
bool compare(pair<int, string> a, pair<int, string> b) {
return a.first < b.first;
}
int main()
{
pair<int, string> tmp;
vector<pair<int, string>> arr;
int testCase;
cin >> testCase;
for (int i = 0; i < testCase; i++) {
cin >> tmp.first >> tmp.second;
arr.push_back(tmp);
}
stable_sort(arr.begin(), arr.end(), compare);
for (int i = 0; i < testCase; i++) {
cout << arr[i].first << " " << arr[i].second << "\n";
}
}