본문 바로가기

Algorithm_BOJ(백준)/정렬

[백준 5635 c++ OO] 생일

728x90
반응형

내 풀이

-sort 함수의 정렬 순서가 pair의 앞쪽부터 정렬한다는 사실을 모르고 일일이 정렬 함수 만들어 품

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
37
38
39
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring> // memset 헤더
using namespace std;
// [백준 5635 c++ O] 생일  
// 문제:
// 접근: 벡터에 pair 형으로 저장 -> sort 로 나이순 정렬 
// 풀이: 
int n,d,m,y;
string name;
vector<pair<pair<stringint>pair<intint>>> a; // 이름,날짜,월,년
 
bool mysort(pair<pair<stringint>pair<intint>> b, pair<pair<stringint>pair<intint>> c) {
    if (b.second.second != c.second.second) { // 년 오름차순
        return b.second.second < c.second.second;
    }
    else if (b.second.first != c.second.first) { // 월 오름차순
        return b.second.first < c.second.first;
    }
    else if (b.first.second != c.first.second) { // 일 오름차순
        return b.first.second < c.first.second;
    }
}
int main() {
    ios::sync_with_stdio(false); // 계산시간 단축 // cin,scanf 같이 쓰면 오류
    cin.tie(nullptr); cout.tie(nullptr);// 입출력 시간 단축 // 이것을 쓰면 scanf,printf섞어 쓰면 안됨
 
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> name >> d >> m >> y;
        a.push_back({ {name,d }, { m,y } });
    }
    sort(a.begin(), a.end(), mysort);
    cout << a[n - 1].first.first << '\n';
    cout << a[0].first.first << '\n';
    return 0;
}
cs

 

 

2. 참고 풀이

: sort의 앞 원소부터 년 월 일 로 하면 자연스럽게 나이가 많은 순으로 정렬된다.

 

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
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring> // memset 헤더
using namespace std;
// [백준 5635 c++ OO] 생일  
// 문제:
// 접근: 벡터에 pair 형으로 저장 -> sort 로 나이순 정렬 
// 풀이: 
// 개념: 
// sort() 함수는 벡터 pair의 앞 원소부터 정렬 비교한다.
int n,d,m,y;
string name;
vector<pair<pair<intint>pair<intstring>>> a; // 년,월,일,이름 // 정렬이 앞 원소부터 적용되서 이렇게 순서잡음
 
int main() {
    ios::sync_with_stdio(false); // 계산시간 단축 // cin,scanf 같이 쓰면 오류
    cin.tie(nullptr); cout.tie(nullptr);// 입출력 시간 단축 // 이것을 쓰면 scanf,printf섞어 쓰면 안됨
 
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> name >> d >> m >> y;
        a.push_back({ {y,m}, { d,name } });
    }
    sort(a.begin(), a.end());
    cout << a[n - 1].second.second << '\n';
    cout << a[0].second.second << '\n';
    return 0;
}
cs
반응형

'Algorithm_BOJ(백준) > 정렬' 카테고리의 다른 글

[백준 2693 c++ O] N번째 큰 수  (0) 2021.09.06
[백준 2711 c++ O] 세수정렬  (0) 2021.08.30
[백준 11004 c++ O] K번째 수  (0) 2021.08.06
[백준 11652 c++ V] 카드  (0) 2021.08.06
[백준 10825 c++ O] 국영수  (0) 2021.08.06