PS/BOJ

[백준 BOJ][sort] 11651 좌표 정렬하기 2

Jubil 2018. 7. 24. 01:02
반응형

11651_좌표 정렬하기 2

링크

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

 

풀이


 

좌표를 먼저 y 좌표가 증가하는 순으로, y좌표가 같으면 x좌표가 증가하는 순으로 정렬하는 문제입니다.

 

우선 좌표를 표현하기 좋은 자료구조인 pair<int, int>[]를 사용하겠습니다.

 

sort()3번째 인자인 compare 함수를 정의해줘야 하는데요.

bool compare(pair<int, int> p1, pair<int, int> p2)를 정의해줍시다.

 

1.     y가 증가하는 순으로 -> if(p1.second != p2.second) return p1.second < p2.second;

2.     y가 같다면 x가 증가하는 순으로 -> return p1.first < p2.first;

 

pair 생성은 make_pair(x, y)로 할 수 있습니다.

 

 

코드

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

//11651_좌표 정렬하기 2

#include <cstdio>

#include <iostream>

#include <algorithm>

#include <string>

using namespace std;

 

pair<intint> p[100000];

 

bool compare(pair<intint> p1, pair<intint> p2) {

    if (p1.second != p2.second) {

        return p1.second < p2.second;

    }

 

    return p1.first < p2.first;

}

 

int main() {

    int n;

    int x, y;

 

    cin >> n;

 

    for (int i = 0; i < n; ++i) {

        scanf("%d %d"&x, &y);

 

        p[i] = make_pair(x, y);

    }

 

    sort(p, p + n, compare);

 

    for (int i = 0; i < n; ++i) {

        printf("%d %d\n", p[i].first, p[i].second);

    }

 

    return 0;

}

Colored by Color Scripter

cs

 

 


 


반응형

'PS > BOJ' 카테고리의 다른 글

[백준 BOJ][queue] 10845 큐  (0) 2018.07.26
[백준 BOJ][stack] 10828 스택  (0) 2018.07.26
[백준 BOJ][sort] 11650 좌표 정렬하기  (0) 2018.07.24
[백준 BOJ][sort] 1181 단어 정렬  (0) 2018.07.24
[백준 BOJ][sort] 11931 수 정렬하기 4  (0) 2018.07.24