BOJ - 11650 - 좌표 정렬하기

ggh·2022년 5월 11일
0

백준

목록 보기
5/112

BOJ - 11651 - 좌표 정렬하기 2

문제


11650번: 좌표 정렬하기

SOL


  • x 좌표 끼리 정렬 후 중복 발생시 y 좌표를 기준으로 정렬
    • pair을 사용하여 2개의 자료형을 받을 수 있는 자료형 생성
      • pair<int, int>
  • sort의 compare를 사용하여 조건문을 만들어 줌
    bool compare(pair<int,int> a,
                 pair<int,int> b)
    {
        if(a.first == b.first)
            return a.second < b.second;
        return a.first < b.first; 
    }

구현


#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

bool compare(pair<int,int> a,
             pair<int,int> b)
{
    if(a.first == b.first)
        return a.second < b.second;
    return a.first < b.first; 
}

int main()
{
    int num;
    int x, y;
    vector<pair<int,int>> xy_list;
    cin >> num;
    for(int i=0; i < num; i++)
    {
        cin >> x >> y;
        xy_list.push_back(pair<int, int>(x, y));
    }
    sort(xy_list.begin(), xy_list.end(), compare);
    for(int i=0; i < xy_list.size(); i++)
        cout << xy_list[i].first << " " << xy_list[i].second << endl;
}

출력은 정상적으로 되지만... 시간초과라 하니 std::cin, cout을 scanf, printf함수로 바꿔보자...

구현 - scanf, printf


#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

bool compare(pair<int,int> a,
             pair<int,int> b)
{
    if(a.first == b.first)
        return a.second < b.second;
    return a.first < b.first; 
}

int main()
{
    int num;
    int x, y;
    vector<pair<int,int>> xy_list;
    scanf("%d", &num);
    for(int i=0; i < num; i++)
    {
        scanf("%d%d", &x, &y);
        xy_list.push_back(pair<int, int>(x, y));
    }
    sort(xy_list.begin(), xy_list.end(), compare);
    for(int i=0; i < xy_list.size(); i++)
        printf("%d %d\n", xy_list[i].first, xy_list[i].second);
}

출력

5
3 4
1 1
1 -1
2 2
3 3
--------
1 -1
1 1
2 2
3 3
3 4

비슷한 문제 : 11651 - 좌표 정렬하기 2


위와 같은 방법으로 구현함.

11651 - 좌표 정렬하기 2 - 구현


#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

bool compare(pair<int,int> a,
             pair<int,int> b)
{
    if(a.second == b.second)
        return a.first < b.first;
    return a.second < b.second; 
}

int main()
{
    int num;
    int x, y;
    vector<pair<int,int>> xy_list;
    scanf("%d", &num);
    for(int i=0; i < num; i++)
    {
        scanf("%d%d", &x, &y);
        xy_list.push_back(pair<int, int>(x, y));
    }
    sort(xy_list.begin(), xy_list.end(), compare);
    for(int i=0; i < xy_list.size(); i++)
        printf("%d %d\n", xy_list[i].first, xy_list[i].second);
}

출력


5
0 4
1 2
1 -1
2 2
3 3
------
1 -1
1 2
2 2
3 3
0 4

Reference & 다른 PS 모음집


C++ STL sort ( )

https://github.com/ggh-png/PS

profile
See you in a minute. : )

0개의 댓글