본문 바로가기
백준/C++

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

by 대니스 2022. 8. 9.

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

 

10814번: 나이순 정렬

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

www.acmicpc.net

소스 코드 :

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

class Person
{
public:
	string name;
	int age;
	int order;
};

bool compare(Person a, Person b)
{
	if (a.age == b.age)
		return a.order < b.order;
	else
		return a.age < b.age;
}

int main()
{
	int information = 0;
	cin >> information;
	vector<Person> p(information);

	for (int i = 0;i < information;i++)
	{
		cin >> p[i].age >> p[i].name;
		p[i].order = i + 1;
	}

	sort(p.begin(), p.end(),compare);

	for (int i = 0;i < information;i++)
		cout << p[i].age << ' ' << p[i].name << '\n';
}

마무리 : 나이와 이름의 정보를 가지고 있기 때문에 클래스를 사용했다. 구조체를 사용해도 상관없다. 그리고 sort 함수를 사용하는데 이 때 나이가 같으면 이름 순으로 정렬해야하므로 compare함수를 직접 만들어서 사용한다.