자기개발👨‍💻/코딩 알고리즘

[C++] 백준 11651 // <vector><map>

천숭이 2022. 3. 16. 18:59

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

 

11651번: 좌표 정렬하기 2

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

www.acmicpc.net

#include <iostream>
#include <vector>
#include <algorithm>
#include <utility> 
using namespace std;

bool compare(pair<int,int>a, pair<int,int>b){
	if (a.second == b.second){ // y좌표가 같으면 
		return a.first < b.first; 
	}
	else{
		return a.second < b.second;
	}
}

int main(){
	vector<pair<int, int> > v;
	vector<pair<int, int> >::iterator iter;
	int n, a, b;
	cin >> n;
	
	for(int i=0;i<n;i++){
		cin >> a >> b;
		v.push_back(make_pair(a,b));
	}
	
	sort(v.begin(), v.end(), compare);
	
	for(iter=v.begin(); iter!=v.end(); iter++){
		cout<<iter->first<<" "<<iter->second<<"\n";
	}	
	
}

- vector 내부의 원소를 원소쌍 pair로 담아주었다

- 문제에서의 정렬 조건이 y좌표 증가하는 순이지만, y좌표가 같을땐 x좌표 증가하는 순이다.

- 정렬 조건 두가지를 한꺼번에 다루기 위해서는 compare 옵션함수의 내용을 수정해야한다.