알고리즘 문제풀이

백준 10814번 나이순 정렬 C++/정렬/실버5

yoogani 2023. 10. 24. 20:20

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

 

10814번: 나이순 정렬

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

www.acmicpc.net

 

나이가 어린순으로 출력한다.

만약 나이가 같다면 먼저 가입한 애부터 출력한다.

 

정렬을 위해 구조체를 사용했다.

나이가 같으면 인덱스가 큰 애가 먼저 오도록 정렬한다.

그리고 나이순으로 나이가 어린 애가 먼저 오도록 정렬한다.

 

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

using namespace std;

struct Data {
	int idx;
	int age;
	string name;
	
	Data(int x, int z,string y) {
		idx = x;
		age = z;
		name = y;
	}

	bool operator < (const Data& b) const {
		if (age == b.age) return idx < b.idx;
		return age < b.age;
	}
};


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

	int n, a;
	string str;

	cin >> n;

	vector<Data> map;

	for (int i = 0; i < n; i++) {
		cin >> a >> str;
		map.push_back(Data(i, a, str));
	}
	sort(map.begin(), map.end());

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

	return 0;
}