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

전에 풀었던 문제에서 x좌표의 오름차순에서 y좌표의 오름차순으로 바뀐 문제이다. 정렬함수만 살짝 바꿔주면 풀 수 있는 문제이다. pair에서 first보다 second를 먼저 비교하고 second가 같을 경우 first를 비교해주면 된다.

 

정답코드

#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

vector<pair<int, int>> vp;

bool cmp(pair<int, int> p1, pair<int, int> p2) {
    if (p1.second == p2.second) {
        return p1.first < p2.first;
    }
    return p1.second < p2.second;
}

int main() {
    int n;
    scanf("%d", &n);

    vp.reserve(n);

    for (int i = 0; i < n; i++) {
        int x, y;
        scanf("%d %d", &x, &y);
        vp.push_back({ x, y });
    }

    sort(vp.begin(), vp.end(), cmp);

    for (int i = 0; i < n; i++) {
        printf("%d %d\n", vp[i].first, vp[i].second);
    }

    return 0;
}

+ Recent posts