작심 24/7

[백준] 10814번 나이순 정렬 본문

백준

[백준] 10814번 나이순 정렬

모닝수박 2020. 5. 23. 22:17
 

10814번: 나이순 정렬

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

www.acmicpc.net

vector의 pair기능과 compare함수를 이용하면 쉽게 풀 수 있는 문제이다.

compare 없이 그냥 sort를 해주면 vector의 first를 기준으로 정렬되기 때문에

second.first(나이)가 같으면 second.second(인덱스 값)이 증가하는 순으로 정렬시키도록

compare함수를 작성해주면 끝

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
vector < pair <string, pair <int, int> > > v;

bool compare(pair <string, pair <int, int> > a, pair <string, pair <int, int> > b) {
	if (a.second.first == b.second.first) {
		return a.second.second < b.second.second;
	}
	else return a.second.first < b.second.first;
}

int main() {
	int N;
	cin >> N;

	int age;
	string name;
	for (int n = 0; n < N; n++) {
		cin >> age >> name;
		v.push_back(pair<string, pair<int, int> >(name, pair<int, int>(age, n)));
	}
	sort(v.begin(), v.end(), compare);

	for (int i = 0; i < N; i++)cout << v[i].second.first << " " << v[i].first << "\n";

	return 0;
}
Comments