[백준 10814번] 정렬 - 나이순 정렬 (구조체/Pair 자료구조의 compare 함수!)
컴퓨터/알고리즘

[백준 10814번] 정렬 - 나이순 정렬 (구조체/Pair 자료구조의 compare 함수!)

목차

  1. sort란
  2. 그럼 pair/구조체 각자 정렬은 어떻게 하는데
  3. compair함수 작성법 사용법
  4. 나이순 정렬 풀이

1. sort(시작점, 목적지, compare 함수 );

정렬문제에서는 총 2가지 정렬이 있다!

  1. 오름차순 (기본으로 아무것도 안적으면 실행됨)
  2. 내림차순 (일명 greater<자료형>)

☆참고☆

http://www.cplusplus.com/reference/algorithm/sort/?kw=sort

 

sort - C++ Reference

custom (2)template void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

www.cplusplus.com

2. 아니 근데 compare 함수 는 뭡니까? -> pair 또는 구조체 배열 갖고 놀기

예를 들어서
pair<자료형,자료형> 이나 struct 구조체 를 구성하는
요소(원소/구조체에 포함된 변수든 뭐든.. ㅋㅋ)를 내멋대로 정렬하고 싶다!

 

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

 

11651번: 좌표 정렬하기 2

첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.

www.acmicpc.net

좌표를 y좌표가 증가하는 순으로,
y좌표가 같으면 x좌표가 증가하는 순서로 정렬

란다.. 이렇게 요소들의 정렬상태를

  • 하나는 오름차순
  • 다른 하나는 내림차순
    이런식으로 하려면 바로 compair 함수 를 사용하는것이다.


3. 아니 그래서 어떻게 작성하라고?

[함수] _compair 함수_는 리턴형이 bool형이다! (일단 오름차순만 적어봄)

(pair/구조체 변수 A, B가 있을때)
이 표기는 외워두자!

  • A < B (오름차순)
  • A > B (내림차순)

그럼 기본적으로 어떻게 작성해야하는지 보자

1. 1차 컨테이너 오름차순

1
2
3
4
bool compare(int a, int b)
{
    return a < b;
}
 

2. pair 컨테이너 오름차순

1
2
3
4
5
6
7
bool compare(pair<int,int> a, pair<int,int> b)
{
    if(a.first != b.first)
        return a.first < b.first;
    else if(a.first == b.first )
        return a.second < b.second;
}
cs

3. 구조체 컨테이너 오름차순

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
typedef struct _Triple{
    int one;
    int two;
    int three;
}Triple;
 
bool compare(Triple a, Triple b)
{
    if(a.one != b.one)
        return a.one < b.one;
    else if(a.one == b.one )
    {
        if(a.two != b.two)
            return a.two < b.two;
        else if(a.two == b.two)
            return a.three < b.three
    }
        
}
cs

... 사실 내가 나중에 봤을떄 이해하기 편하라고 써서.. 이해 안되면 ㅈㅅ.

4. 그래서 나이순 정렬은 어떻게 풀었니

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
40
41
42
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
 
typedef struct AgeName {
    int num;
    int age;
    string name;
}AN;
 
vector<AgeName> v;
 
bool cmp(AgeName a, AgeName b)
{
    if (a.age == b.age)
        return a.num < b.num;
    return a.age < b.age;
}
 
int main()
{
    ios::sync_with_stdio(false); cin.tie(NULL);
    int N; cin >> N;
    for (int i = 0; i < N; i++)
    {
        int a; string str;cin >> a >> str;
        v.push_back({ i,a,str });
    }
 
    sort(v.begin(), v.end(), cmp);
 
    for (int i = 0; i < N; i++){
        cout << v[i].age << ' ' << v[i].name << '\n';
    }
    
    return 0;
}
 
cs

..너의 잘못을 알아라

이거 처음에 compare 함수 쓸때 

a와 b 랑 비교 했었어야 했는데 깜빡하고

a랑 a 똑같은거 비교해서 틀리고 말았다.. 조심해