프로그래밍 공부/백준 (C++)

[C++/백준 10814번] 나이순 정렬

Rocketbabydolls 2023. 8. 8. 19:51

https://www.acmicpc.net/problem/10814

 

10814번: 나이순 정렬

온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한 사람이 앞에 오는 순서로 정렬하는 프로그램을

www.acmicpc.net

 

해결 방법

 

   sort는 정렬에 데이터의 순서를 보장하지 않는다. 

 

sort는 퀵 정렬을 기반으로 하고,

stable_sort 는 합병 정렬을 기반으로 하기 때문에 원소의 순서를 보장한다. 여기서는 가입 순서가 중요하기 때문에, 순서가 바뀌면 안 된다.

 

따라서 stable_sort 를 사용하면 쉽게 해결 가능하다.

 

#include <iostream>
#include <vector>
#include <algorithm>


using namespace std;
vector<pair<int, string>> P;

bool cmp(const pair<int, string> &a, const pair<int, string> &b)
{
	if (a.first < b.first)
	{
		return true;
	}
	else if (a.first > b.first)
	{
		return false;
	}
	else
		return false;

}
int main() {
	int N;

	cin >> N;

	for (int i = 0; i < N; i++)
	{
		
		string input;
		int age;
		cin >> age;
		cin >> input;

		P.push_back({age, input});

	}

	stable_sort(P.begin(), P.end(), cmp);

	
	for (auto i : P)
		cout << i.first << " " << i.second << "\n";

	return 0;
}