본문 바로가기

알고리즘/Baekjoon Online Judge

[stable_sort]https://www.acmicpc.net/problem/10814

01. 문제

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

 

10814번: 나이순 정렬

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

www.acmicpc.net

 

02. 코드

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define endl "\n";

vector<pair<int, string>> v;

bool cmp(pair<int, string> a, pair<int, string> b)
{
	return a.first < b.first;
}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);

	//input
	int n;
	cin >> n;
	for (int i = 0; i < n; ++i) {
		int a;
		string b;
		cin >> a >> b;
		v.push_back({ a, b });
	}

	//stable_sort
	stable_sort(v.begin(), v.end(), cmp);

	//output
	for (int i = 0; i < v.size(); ++i) {
		cout << v[i].first << " " << v[i].second << endl;
	}
}

 

03. 전략

stable_sort에 의해 동등한 원소의 상대적 위치가 그대로 유지된다.