Algorithm/BOJ

[백준 알고리즘/BOJ/C++] 11650, 11651 좌표 정렬하기

pinevienna 2021. 1. 26. 13:31

 

 

이렇게 x, y를 입력받고

11650 : x 기준으로 정렬, x가 같으면 y기준으로 정렬하는 문제

11651 : y 기준으로 정렬, y가 같으면 x기준으로 정렬하는 문제

 

벡터를 안쓰던 때라... 모르겠어서 검색해보니 '연산자 오버로딩'이 나왔다

 

 

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
#include <iostream>
#include <algorithm>
 
using namespace std;
 
class Coord {
public:
    int x;
    int y;
 
    bool operator <(Coord xy) { //연산자 오버로딩
        if (this->== xy.x)
            return this->< xy.y;
        return this->< xy.x;
    }
};
 
int main() {
    int N;
    cin >> N;
    Coord* coords = new Coord[N];
 
    for (int i = 0; i < N; i++) {
        cin >> coords[i].x >> coords[i].y;
    }
 
    sort(coords, coords + N);
 
    for (int i = 0; i < N; i++) {
        cout << coords[i].x << " " << coords[i].y << "\n";
    }
 
}
cs

 

11651은 연산자 오버로딩 부분만 반대로 바꿔주면 된다

 

1
2
3
if (this->== xy.x) 
   return this->< xy.y; 
return this->< xy.x;
cs

 

이렇게!!

 

11650은 벡터를 쓰는게 더 편할 것 같다

난 이제 벡터를 쓸 줄 아는 멋쟁이니까

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int main() {
    int N, x, y;
    cin >> N;
 
    vector<pair<intint>> v;
    while (N--) {
        cin >> x >> y;
        v.push_back(pair<intint>(x, y));
    }
 
    sort(v.begin(), v.end());
 
    for (int i = 0; i < v.size(); i++) {
        cout << v[i].first << ' ' << v[i].second << "\n";
    }
}
cs

 

근데 방금 돌려보니 실행시간도 더 길고, 메모리도 더 많이 사용한다..

vector가 좀 그런가? sort 하는건 똑같은데.. 벡터 멋쟁이 취소

그리고 second를 기준으로 정렬할 땐 똑같이 오버로딩 해야할 것을..ㅎㅎ (아마도?!)

 

연산자 오버로딩에 조금 더 익숙해져야겠다