Algorithm/Baekjoon

[BOJ 1863] ์Šค์นด์ด๋ผ์ธ ์‰ฌ์šด๊ฑฐ

sun_young 2024. 4. 7. 16:30

๐Ÿ“ƒ ๋ฌธ์ œ

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

 

1863๋ฒˆ: ์Šค์นด์ด๋ผ์ธ ์‰ฌ์šด๊ฑฐ

์ฒซ์งธ ์ค„์— n์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ n ≤ 50,000) ๋‹ค์Œ n๊ฐœ์˜ ์ค„์—๋Š” ์™ผ์ชฝ๋ถ€ํ„ฐ ์Šค์นด์ด๋ผ์ธ์„ ๋ณด์•„ ๊ฐˆ ๋•Œ ์Šค์นด์ด๋ผ์ธ์˜ ๊ณ ๋„๊ฐ€ ๋ฐ”๋€Œ๋Š” ์ง€์ ์˜ ์ขŒํ‘œ x์™€ y๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (1 ≤ x ≤ 1,000,000. 0 ≤ y ≤ 500,000) ์ฒซ

www.acmicpc.net


๐Ÿ’ป ์ฝ”๋“œ

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

int N;
vector<int> v;
stack<int> s;
int cnt = 0;

int main() {
	cin >> N;

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

	for (int i = 0; i < v.size(); i++) {
		while (!s.empty() && s.top() >= v[i]) {
			if(s.top() > v[i])cnt++;
			s.pop();
		}
		s.push(v[i]);
	}
	cout << cnt << '\n';
}

 

๋ฉ”๋ชจ๋ฆฌ ๋ฐ ์‹œ๊ฐ„


๐Ÿ’ก ํ’€์ด

- vector<int> v; // ์ขŒํ‘œ์˜ y๊ฐ’ ์ €์žฅ

- stack<int> s; // ์Šค์นด์ด๋ผ์ธ ๊ณ ๋„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ €์žฅ

 

 

1. ๋งˆ์ง€๋ง‰ ๊ฑด๋ฌผ๊นŒ์ง€ ํ™•์ธํ•˜๊ธฐ ์œ„ํ•ด ์ž…๋ ฅ ๋ฐ›์€ y์ขŒํ‘œ ์ €์žฅ ํ›„ 0๊ฐ’์„ ๋งˆ์ง€๋ง‰์— ์ €์žฅ

    v.push_back(0);

 

2. ์ž…๋ ฅ๋ฐ›์€ y ์ขŒํ‘œ ๋งŒํผ (vector v์˜ ํฌ๊ธฐ) ๋ฐ˜๋ณต

 

3. stack์ด ๋น„์–ด์žˆ์ง€ ์•Š๋‹ค๋ฉด

     3-1. stack.top()์ด ํ˜„์žฌ y์ขŒํ‘œ(v[i])๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™์œผ๋ฉด stack.pop()

     3-2. stack.top()์ด ํ˜„์žฌ y์ขŒํ‘œ(v[i])๋ณด๋‹ค ํฌ๋ฉด ๊ฑด๋ฌผ ํ•˜๋‚˜๊ฐ€ ๋๋‚œ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— cnt(๊ฑด๋ฌผ ๊ฐœ์ˆ˜)๋ฅผ ์ฆ๊ฐ€

     3-3. stack.top()๋ณด๋‹ค ํ˜„์žฌ y์ขŒํ‘œ(v[i])๊ฐ€ ์ž‘์œผ๋ฉด ํ˜„์žฌ y์ขŒํ‘œ๋ฅผ stack์— push

     → stack์— ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ y์ขŒํ‘œ ๊ฐ’์„ ์ €์žฅ

 

 

'Algorithm > Baekjoon' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[BOJ 22871] ์ง•๊ฒ€๋‹ค๋ฆฌ ๊ฑด๋„ˆ๊ธฐ (large)  (0) 2024.03.17
[BOJ 2110] ๊ณต์œ ๊ธฐ ์„ค์น˜  (0) 2024.03.14