[백준] 10814번 - 나이순 정렬 [Java][C++]
[백준] 10814번 - 나이순 정렬 [Java][C++]
1. 문제 풀이
나이와 이름이 주어진 회원들에 대해 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한 사람이 앞에 오는 순서로 정렬하는 문제로 언어별 정렬을 활용하면 간단하게 해결할 수 있다.
2. 코드
1. 정렬 [Java]
User 클래스를 만들어서 나이와 이름 정보를 저장하고 Array.sort 메서드에서 람다식을 활용해서 정렬했다. 이때 나이를 기준으로만 정렬했는데 Java에서 객체 정렬은 안정 정렬이라 나이가 같으면 자연스럽게 입력 순서대로 정렬이 된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import java.io.*;
import java.util.*;
public class Main {
static class User {
int age;
String name;
public User(int age, String name) {
this.age = age;
this.name = name;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int N = Integer.parseInt(br.readLine());
User[] users = new User[N];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
users[i] = new User(Integer.parseInt(st.nextToken()), st.nextToken());
}
Arrays.sort(users, ((o1, o2) -> Integer.compare(o1.age, o2.age)));
for (User user : users) {
sb.append(user.age).append(" ").append(user.name).append("\n");
}
System.out.println(sb);
}
}
2. 정렬 [C++]
pair<int, string> 를 활용해서 회원 정보를 다루었다. pair 의 기본 정렬 기준하고는 다르기 때문에 나이 순으로 정렬하도록 람다식을 짜주었고 sort 는 불안정 정렬이기에 stable_sort 함수를 활용했다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<pair<int, string>> v(n);
for (auto& p : v) cin >> p.first >> p.second;
stable_sort(v.begin(), v.end(), [](const pair<int, string>& a, const pair<int, string>& b) {
return a.first < b.first;
});
for (auto p : v) {
cout << p.first << ' ' << p.second << '\n';
}
}
3. 풀이 정보
1. 정렬 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 544 ms | 45160 KB | 972 B |
2. 정렬 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 40 ms | 7900 KB | 451 B |
This post is licensed under CC BY 4.0 by the author.