본문 바로가기
코딩테스트 준비/백준

[백준 11650번][C++] 좌표 정렬하기

by 스테디코디스트 2023. 7. 28.
반응형

<문제 소개>


<소스 코드>

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <map>
#include <unordered_map>
#include <cmath>
#include <stack>
#include <queue>
#include <algorithm>
#include <cstdlib>
using namespace std;

int main()
{
	// 쓰레드 환경이 아닐때 버퍼를 분리하여 처리속도를 빠르게 해줌
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int N;
	cin >> N;

	map<int, vector<int>> XY;

	for (int i = 0; i < N; i++)
	{
		int x, y;
		cin >> x >> y;

		XY[x].push_back(y);
	}	

	for (map<int, vector<int>>::iterator iter = XY.begin(); iter != XY.end(); iter++)
	{
		sort(iter->second.begin(), iter->second.end());

		for (int i = 0; i < iter->second.size(); i++)
		{
			cout << iter->first << " " << iter->second[i] << "\n";
		}
	}

	return 0;
}

<풀이과정>

1. N을 입력받고, key로 int형 value로 vector<int>형을 갖는 map, XY를 선언한다.

2. N번 반복하며 x,y를 입력받고, map의 key가 x인 벡터에 y를 추가해준다.

3. 맵은 key값이 자동으로 정렬되는 컨테이너이므로 이제 key값에 따른 y값들만 정렬해주면 된다.

4. iterator를 이용해 map의 key값을 돌면서 key별로 가지는 벡터들을 sort를 이용해 정렬해주고, 정렬된 벡터의 원소를 돌면서 해당 key값과 함께 벡터의 값을 차례로 출력해준다.

 


<코멘트>

처음에 어떻게 풀어야할지 감이 잘 안잡혔는데 맵을 컨테이너로 설정하니깐 이후로 쉽게 풀렸다!

 


<제출결과>