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

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

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

<문제 소개>

 


<소스 코드>

#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[y].push_back(x);
	}	

	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->second[i] << " " << iter->first << "\n";
		}
	}

	return 0;
}

<풀이과정>

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

2. N만큼 반복하며 x,y를 입력받고 XY에 넣는데, map은 key값에 의해 정렬되므로 y값으로 우선정렬하기 위해 key값으로 y를 넣고 value값으로 x를 넣어준다.

3. 다음으로 XY의 원소들을 돌면서, 같은 벡터내의 원소들 즉, y가 같은 숫자일때 x의 값들을 sort를 이용해 정렬해주고, 정렬된 벡터의 x와 y를 차례로 출력한다.

4. 이때 y가 key값에 해당하므로 value값인 x값을 먼저 출력하고 공백을 출력하고 key값인 y값을 출력하는 순으로 진행한다.


<코멘트>

좌표 정렬하기 1이랑 x,y가 바뀐 문제여서 같은 방식으로 간단하게 해결했다!


<제출결과>