PS/정렬 알고리즘[Sort]

백준 1374 강의실(c++)

SeungbeomKim 2022. 7. 11. 11:27
반응형

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

 

1374번: 강의실

첫째 줄에 강의의 개수 N(1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 줄마다 세 개의 정수가 주어지는데, 순서대로 강의 번호, 강의 시작 시간, 강의 종료 시간을 의미한다. 강의

www.acmicpc.net

<코드>

#include <iostream>
#include <algorithm>
#include <utility>
#include <queue>
using namespace std;
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>lectures;
priority_queue<int,vector<int>,greater<int>>rooms;
int main()
{
	int n;
	cin>>n;
	int number, starttime,endtime;
	for(int i=0;i<n;i++)
	{
		cin>>number>>starttime>>endtime;
		lectures.push(make_pair(starttime,endtime));
	}
	rooms.push(lectures.top().second);
	lectures.pop();
	while(lectures.size())
	{
		if(rooms.top()<=lectures.top().first)
		{
			rooms.push(lectures.top().second);
			rooms.pop();
		}
		else
		{
			rooms.push(lectures.top().second);
		}
		lectures.pop();
	}
	cout<<rooms.size();
}

<풀이과정>

이 문제는 우선순위 큐를 활용한 문제이다. 강좌마다 시간이 겹치게 된다면(시작시간 = 종료시간 제외) 방을 추가해주면 된다. 그러기 위해서는 종료시간이 가장 빠른 것(second)을 우선적으로 추가해주는 우선순위 큐와 강의실은 시작시간이 가장 빠른것을 기준으로 추가해주는 우선순위 큐를 만들어주는 것이 핵심이다. while문 안에 if부분은 강좌시간이 겹치지 않으면 방의 개수를 그대로 해주고, 강좌시작시간을 갱신해주는 부분이다. 그렇지 않으면 방의 개수를 추가해주면 된다.  

반응형

'PS > 정렬 알고리즘[Sort]' 카테고리의 다른 글

18870 좌표 압축(c++)  (0) 2022.07.13
백준 20291 파일 정리(c++)  (0) 2022.07.12
백준 5635 생일(c++)  (0) 2022.07.07
백준 10989 수 정렬하기 3(c++)  (1) 2022.07.07
백준 2075 N번째 큰 수  (1) 2022.07.07