티스토리 뷰

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

 

11650번: 좌표 정렬하기

첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다.

www.acmicpc.net

 

C++ 정답 소스

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

using namespace std;

int main()
{
  ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);
  vector<pair<int, int>> v;
  // v.push_back(pair<int, int>(1, -1));
  int n, x, y;
  cin >> n;

  for(int i = 0; i < n; i++){
    cin >> x >> y;
    v.push_back(pair<int, int>(x, y));
  }

  sort(v.begin(), v.end());
  
  for(int i = 0; i < v.size(); i++){
    cout << v[i].first << ' ' << v[i].second << '\n';
  }
}

1. pair를 이용해 int형 값을 두 개 받는 벡터를 생성

2. 입력받은 수 만큼 벡터에 x, y 값 삽입

3. sort를 이용해 오름차순 정렬 - pair를 이용하면 아래 작성한 compare()없이도 문제에서 요구하는 오름차순이 구현되어있다.


C++의  pair가 생각나지 않아 처음에는 다음과 같이 코드를 작성했다.

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

using namespace std;


class xypair{
  public:
  int x, y;

  xypair(int _x, int _y){
    x = _x;
    y = _y;
  }
};

bool comapre(xypair &a, xypair &b){
  if(a.x < b.x){
    return true;
  }
  else if(a.x == b.x){
    if(a.y < b.y) return true;
    else return false;
  }
  else{
    return false;
  }
}


int main()
{
  ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL);

  int n, x, y;
  cin >> n;
  vector<xypair> v;
  for(int i = 0; i < n; i++){
    cin >> x >> y;
    v.push_back(xypair(x,y));
  }
  sort(v.begin(), v.end(), comapre);

  for(int i = 0; i < n; i++){
    cout << v[i].x << " " << v[i].y << '\n';
  }
}

1. 정수 두 개를 담는 클래스, 생성자 선언

2. 입력받은 횟수 N 만큼 x, y 값을 생성자로 전달

3. 두 값을 순차비교해 정렬하는 compare와 sort를 이용해 정렬

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
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
글 보관함