Useful STL - Pair에 대하여

최인규·2023년 7월 18일
0

C/C++

목록 보기
6/7
post-thumbnail

추후에 학습할 Graph, 그 그래프를 활용한 완전 탐색 알고리즘인 BFS/DFS를 응용하여 문제 풀이를 하다보면 2차원 배열을 좌표처럼 사용하거나 이해한 상태로 진행해야 유리할 때가 매우 많다.

언제까지나 arr[n][m]형태로 작성하기는 귀찮을 뿐더러도 직관적으로 잘 와닿지 않기에 소개할 STL인 Pair를 적극적으로 사용하면 좋은 듯하다.

1. 헤더파일

#include <utility>

pair를 사용하기 위해서는 utility 헤더파일을 include 해주면 된다.

2. 사용법

선언방식과 좌표처럼 사용하는 방법 2가지

# 첫번째 방식
pair<int,int> x;

x.fisrt = 1;
x.second = 3;

pair뜻처럼 쌍으로 데이터를 처리하기 위해서 pair를 사용하기 때문에 선언 시에 두 가지 자료형을 함께 <> 안에 표현해줘야 한다.
(보통 좌표 사용시에 pair를 쓰기에 int,int로 예시를 든다)

또한, 첫번째, 두번째 데이터에 각각 접근하기 위해서 first,second를 사용한다는 점도 기억하며 좋다!

# 두번째 방식
pair<int,int> y;
y = make_pair(1,3);

위와 다르게 make_pair(data1, data2)의 내장함수를 사용하면 바로 집어넣어서 사용할 수 있다.

3. 응용 (feat. 백준 28236)

다음 문제를 억지로 좌표처럼 이해한 후에 풀어보자!

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


destin(목적지인 급식실)의 좌표를 pair 사용하여 표현하고 거리 계산하여 final이라는 벡터에 집어넣고, location에는 각각 반의 좌표를 집어넣었다.

pair를 활용하여 작성한 코드는 다음과 같다.

#include <iostream>
#include <stack>
#include <queue>
#include <algorithm>
#include <vector>
#include <string>
#include <utility>
#include <cmath>

using namespace std;

int main() {
	int floor, room, ban;
	cin >> floor >> room >> ban;
	
	vector<pair<int, int>> location;
	pair<int, int> temp;
	pair<int, int> destin;
	destin.first = room + 1;
	destin.second = 1;

	for (int i = 0; i < ban; i++)
	{
		cin >> temp.second >> temp.first;
		location.push_back(temp);
	}
	
	int distance;
	vector<int> final;
	for (int i = 0; i < location.size(); i++)
	{
		distance = abs(destin.first - location[i].first) + abs(destin.second - location[i].second);
		final.push_back(distance);
	}
	
	//최솟값 찾아주기!
	int min = 10000;
	int result;
	for (int i = 0; i < final.size(); i++)
	{
		if (final[i] < min)
		{
			min = final[i];
			result = i + 1;
		}
	}
	cout << result;
	return 0;
}

pair없이 조금 더 직관적으로 짠 코드는 다음과 같다.

#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <string>
#include <cmath>

using namespace std;

void test() 
{
	int floor, room, ban;
	cin >> floor >> room >> ban;

	//급식실의 위치를 설정함.
	int des_x = room + 1;
	int des_y = 1;

	vector<int> distance;

    //층을 먼저 받는데 층은 y좌표이므로 y->x순으로 입력받음.
    //abs는 차를 절댓값으로 표현하기 위해서 사용함!
	while (ban--)
	{
		int temp_x, temp_y;
		cin >> temp_y >> temp_x;
		int temp = abs(des_x - temp_x) + abs(des_y - temp_y);
		distance.push_back(temp);
	}
    
    //최솟값 찾아서 출력해줌.
	int min = 10000;
	int result;
	for (int i = 0; i < distance.size(); i++)
	{
		if (min > distance[i])
		{
			min = distance[i];
			result = i + 1;
		}
	}
	cout << result << endl;
}
int main() {
	
	test();
	return 0;
}

주의 깊게 볼만한 포인트는 다음과 같다.

1) pair를 원소로 하는 Vector사용
2) 최솟값의 인덱스를 result로 출력해내는 방법
3) pair 데이터 활용

4. 참고할만한 자료

끝으로 pair관련하여 짧게나마 읽어볼만한 링크를 걸어둔다.

https://www.crocus.co.kr/597

4개의 댓글

comment-user-thumbnail
2023년 7월 18일

조은 정보 감사합이다

1개의 답글
comment-user-thumbnail
2023년 7월 18일

글이 잘 정리되어 있네요. 감사합니다.

답글 달기
comment-user-thumbnail
2023년 7월 18일

항상 좋은 글 감사합니다.

답글 달기

관련 채용 정보