ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 정렬_백준_좌표 정렬하기_11650
    Algorithm 2018. 8. 21. 13:56

    기본 자료형 (int, char ---)은 그냥 sort를 하면 되지만 구조체, 클래스는 조건을 더하여 sort를 해야된다.



    방법1 - pair 사용

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
     
    int main() {
        int n;
        cin >> n;
        vector<pair<intint>> value(n); // use pair struct
        for (int i = 0; i < n; i++) {
            scanf("%d %d"&value[i].first, &value[i].second);
        }
        sort(value.begin(), value.end());
        for (int i = 0; i < n; i++) {
            printf("%d %d\n", value[i].first, value[i].second);
        }
     
    }
    cs


    방법2 - 구조체 사용

    비교 함수 cmp를 만들어 줘야 한다.

    이때 함수의 데이터 타입은 bool문이고, 파라미터 변수에는 const와 &이 있어야 된다.

    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
    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
     
    struct Point {
        int x, y;
    };
    //Struct
     
    bool cmp(const Point & u, const Point & v) {
        if (u.x < v.x) {
            return true;
        }
        else if (u.x == v.x) {
            if (u.y < v.y) {
                return true;
            }
        }
        return false;
    }
    //Compare function
     
    int main() {
        int n;
        cin >> n;
        vector <Point> value(n);
        for (int i = 0; i < n; i++) {
            scanf("%d %d"&value[i].x, &value[i].y);
        }
     
        sort(value.begin(), value.end(), cmp);
     
        for (int i = 0; i < n; i++) {
            printf("%d %d\n", value[i].x, value[i].y);
        }
    }
    cs



























    'Algorithm' 카테고리의 다른 글

    정렬_백준_나이순 정렬_10814  (0) 2018.08.21
    정렬_백준_좌표 정렬하기_11651  (0) 2018.08.21
    정렬_백준  (0) 2018.08.21
    수학_백준_조합 0의 개수_2004  (0) 2018.08.21
    수학_백준_팩토리얼 0의 개수_1676  (0) 2018.08.21
Designed by Tistory.