hades

[Baekjoon] 30805๋ฒˆ: ์‚ฌ์ „ ์ˆœ ์ตœ๋Œ€ ๊ณตํ†ต ๋ถ€๋ถ„ ์ˆ˜์—ด ๋ณธ๋ฌธ

๐Ÿ‘Š PS/Algorithm

[Baekjoon] 30805๋ฒˆ: ์‚ฌ์ „ ์ˆœ ์ตœ๋Œ€ ๊ณตํ†ต ๋ถ€๋ถ„ ์ˆ˜์—ด

hades1 2024. 9. 9. 21:35

๐Ÿฅ… ๋ฌธ์ œ

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

 

๐Ÿ” ์„ค๊ณ„

์‚ฌ์ „ ์ˆœ์œผ๋กค ๊ฐ€์žฅ ๋’ค์— ์žˆ๋Š” ๊ณตํ†ต ๋ถ€๋ถ„ ์ˆ˜์—ด์„ ์ฐพ์œผ๋ฉด ๋˜๋ฏ€๋กœ, ๋จผ์ € ๊ฐ ์ˆ˜์—ด์„ ํฐ ์ˆ˜๊ฐ€ ์•ž์— ์˜ค๋„๋ก, ์ˆ˜์˜ ํฌ๊ธฐ๊ฐ€ ๊ฐ™๋‹ค๋ฉด, ์ธ๋ฑ์Šค๊ฐ€ ์ž‘์€ ๊ฒƒ์ด ์•ž์— ์˜ค๋„๋ก ํ•˜๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•ด ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์ด์šฉํ•˜์˜€๋‹ค. 

 

๊ฐ๊ฐ์˜ ์šฐ์„ ์ˆœ์œ„ ํ์—์„œ ์•ž์— ์žˆ๋Š” ํ•˜๋‚˜๋ฅผ ๊บผ๋‚ด๋ฉด์„œ ๊ฐ™๋‹ค๋ฉด, ๊ฒฐ๊ณผ์— ์ถ”๊ฐ€ํ•œ๋‹ค.

๋‹ค๋ฅด๋‹ค๋ฉด, ํฐ ๊ฒƒ์ด ์žˆ๋Š” ์šฐ์„ ์ˆœ์œ„ ํ์—์„œ ํ•˜๋‚˜๋ฅผ ์—†์•ค๋‹ค. ํฐ ๊ฒƒ์ด ๊ณ„์† ๋‚จ์•„์žˆ๋‹ค๋ฉด, ๊ทธ์™€ ๊ฐ™์€ ๊ฒƒ์ด ๋‹ค๋ฅธ ์ชฝ์— ์—†๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

์ฃผ์˜ํ•ด์•ผํ•  ๊ฒƒ์€ ํฌ๊ธฐ ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ๊ฒฐ๊ณผ์— ํฌํ•จ๋˜๋Š” ์ˆ˜๊ฐ€ ๊ฐ๊ฐ ์–‘์ชฝ ์ˆ˜์—ด์—์„œ ์–ด๋Š ์ธ๋ฑ์Šค์— ์œ„์น˜ํ•˜๋Š” ์ง€๋ฅผ ๊ธฐ๋กํ•˜๊ณ , ๊ทธ ์ธ๋ฑ์Šค๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ๊ฒฐ๊ณผ์— ์ถ”๊ฐ€๋  ์ˆ˜ ์—†์œผ๋ฏ€๋กœ ์—†์• ๋Š” ๊ณผ์ •์ด ํฌํ•จ๋˜์–ด์•ผ ํ•œ๋‹ค.

 

๐Ÿ‘Š ํ’€์ด

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

int n, m, number, limit_a_idx = 0, limit_b_idx = 0;

struct compare {
	bool operator()(pair<int, int> a, pair<int, int> b) {
		if (a.first == b.first) {
			return a.second > b.second;
		}
		return a.first < b.first;
	}
};

priority_queue<pair<int, int>, vector<pair<int, int>>, compare> pq1;
priority_queue<pair<int, int>, vector<pair<int, int>>, compare> pq2;
vector<int> result;

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);

	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> number;
		pq1.push({ number, i });
	}

	cin >> m;
	for (int i = 0; i < m; i++) {
		cin >> number;
		pq2.push({ number, i });
	}

	while (!pq1.empty() && !pq2.empty()) {
		if (!pq1.empty() && pq1.top().second < limit_a_idx) {
			pq1.pop();
			continue;
		}
		if (!pq2.empty() && pq2.top().second < limit_b_idx) {
			pq2.pop();
			continue;
		}

		if (pq1.top().first == pq2.top().first) {
			result.push_back(pq1.top().first);
			limit_a_idx = pq1.top().second;
			limit_b_idx = pq2.top().second;
			pq1.pop();
			pq2.pop();
		}
		else if (pq1.top().first > pq2.top().first) {
			pq1.pop();
		}
		else if (pq1.top().first < pq2.top().first) {
			pq2.pop();
		}
	}

	int size = result.size();

	cout << size << "\n";

	for (int i = 0; i < size; i++) {
		cout << result[i] << " ";
	}

	return 0;
}