본문 바로가기

백준 문제 풀이

백준 3015번 오아시스 재결합

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

 

3015번: 오아시스 재결합

첫째 줄에 줄에서 기다리고 있는 사람의 수 N이 주어진다. (1 ≤ N ≤ 500,000) 둘째 줄부터 N개의 줄에는 각 사람의 키가 나노미터 단위로 주어진다. 모든 사람의 키는 231 나노미터 보다 작다. 사람

www.acmicpc.net

스택에 어떤 사람의 키와 키가 그 사람 이상이면 볼 수 있는 사람들의 수를 저장해 둔다.

그리고 그 사람이 볼 수 있는 사람들은 그 사람을 보는 다른 사람들도 볼 수 있으니 수만 세고 스택에서 제거 한다.

 

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

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	int N, height;
	long long int sum = 0;
	cin >> N;
//pair의 first가 키, second가 볼 수 있는 사람의 수
	stack<pair<int, int>> sta;
	for (int i = 0; i < N; i++){
		cin >> height;
//더이상 볼 수 있는 사람이 없을때까지 사람들을 제거
		while (!sta.empty() && sta.top().first < height){
			sum += sta.top().second;
			sta.pop();
		}
//입력받은 사람을 스택에 추가
		if (!sta.empty() && sta.top().first == height){
			sum += sta.top().second;
			int tmp = sta.top().second + 1;
			sta.pop();
			if (sta.size()) sum++;
			sta.push({ height, tmp });
		}
		else{
			if (sta.size()) sum++;
			sta.push({ height, 1 });
		}
	}

	cout << sum;

	return 0;
}

'백준 문제 풀이' 카테고리의 다른 글

백준 22199번 Cat in a tree  (3) 2024.10.10
백준 8872번 빌라봉  (0) 2021.03.17
백준 16894번 약수 게임  (0) 2021.03.16
백준 11404번 플로이드  (0) 2021.03.16
백준 1967번 트리의 지름  (0) 2021.03.16