coding_test/BAEKJOON

백준 11651번 C / C++ 풀이

CodeJin 2021. 11. 29. 16:33

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

https://codejin.tistory.com/102 <- 이 문제의 연장문제. x좌표와 y좌표의 비교 순서를 바꾼다.

 

// C
#include <stdio.h>
#include <stdlib.h>

typedef struct pos{
    int x;
    int y;
}Pos;

int compare (const void * a, const void * b) {
    Pos * p1 = (Pos *)a;
    Pos * p2 = (Pos *)b;

    if (p1->y < p2->y) return -1;
    else if (p1->y > p2->y) return 1;
    else {
        if (p1->x < p2->x) return -1;
        else if (p1->x > p2->x) return 1;
    }
    return 0;
}

int main () {
    int n;
    scanf("%d", &n);
    Pos *arr = (Pos *)malloc(sizeof(Pos) * n);

    for (int i = 0; i < n; i++) 
        scanf("%d %d", &arr[i].x, &arr[i].y);
    
    qsort(arr, n, sizeof(Pos), compare);

    for (int i = 0; i < n; i++)
        printf("%d %d\n", arr[i].x, arr[i].y);
    
}

 

C++의 pair간의 비교는 기본적으로 첫번째 요소를 비교한 후에, 두번째 요소를 비교한다고 했다. 이 점을 이용해서, 굳이 비교함수를 만들지 말고, x, y를 pair에 반대로 넣으면 된다.

 

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
using namespace std;

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

    int n;
    int x, y;
    vector<pair<int, int>> pos;
    vector<pair<int, int>>::iterator iter;

    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> x >> y;
        pos.push_back(make_pair(y, x));
    }
    sort(pos.begin(), pos.end());
    for (iter = pos.begin(); iter != pos.end(); iter++) {
        cout << iter->second << ' ' << iter->first << '\n';
    }
}