๐ ๋งํฌ
https://www.acmicpc.net/problem/20666
20666๋ฒ: ์ธ๋ฌผ์ด์ ์ ์
์์ 2์ ๊ฒฝ์ฐ 4๋ฒ ์์ดํ ์์ด 2๋ฒ ๋ชฌ์คํฐ๋ฅผ ์ก์ผ๋ฉด 3๋งํผ ๋์ด๋๊ฐ ์ฌ๋ผ๊ฐ๋ค. ์ด๋ 1, 2, 5๋ฒ์งธ ๋ชฌ์คํฐ๋ฅผ ์ก์ผ๋ฉด ๊ฐ๊ฐ ๋์ด๋๊ฐ 2, 4, 3 ์ด๋ค. ๋ฐ๋ผ์ ์ด๋ ๊ฒ์์ ๋์ด๋๋ 4 ์ด๋ค. ์ด๊ฒ์ด ํด๋ฆฌ์ดํ
www.acmicpc.net
๐คฏ ํ์ค ํ๊ธฐ
visit ์ฌ๋ํด
๐คท ๋ฌธ์


๐ฉโ๐ป ํ์ด
visit ํ๋ณ๋ฌธ ํ์ค์ด ๋ ํ๋ค๊ฒ ํ๋ ๋ฌธ์
์ญ์ shake! 2020 B๋ฒ ๋ฌธ์ ์ด๋ค.
์ฐ์ ์์ ํ๋ฅผ ์ฐ๋ฉด ํธํ ๋ฌธ์ !
์ฒ์์ item ๊ด๊ณ๋ฅผ ๊ทธ๋ํ ์ฒ๋ผ ์๊ฐํด์ ์ฐ๊ฒฐํ์ฌ ํ๋ ค๊ณ ํ๊ธด ํ๋๋ฐ ๋์ด๋๊ฐ ๋์์ง๋ฉด ํ์์ ์ด๋ป๊ฒ ํด์ผํ ์ง ๋ชจ๋ฅด๊ฒ ์ด์ ์ฒ์๋ถํฐ ๋ค์ ์๊ฐํ๋ค. ๊ทธ๋ฌ๋ ์ค ์์ ์ฒ์๋ถํฐ ๋์ด๋๋ฅผ ์ฌ๋ ค์ ์์ํ๋๊ฒ ์ข์ ๊ฒ ๊ฐ๋ค๋ ์๊ฐ์ด ๋ค์๋ค.
์ฒ์์๋ ๋ฌด์กฐ๊ฑด item ์์ด ์์ํ ํ ๋ tip์ผ๋ก ๋ค์ด์จ ๋ชฌ์คํฐ๋ ๋์ด๋๋ฅผ ๋ฏธ๋ฆฌ ์ฌ๋ ค์ ํ์ ๋ฃ์ด์ฃผ์๋ค.
ํ๋ { ๋์ด๋, ์ธ๋ฑ์ค } ํ์์ผ๋ก ๋ค์ด๊ฐ๊ณ , ๋์ด๋๋ฅผ ๊ธฐ์ค์ผ๋ก min heap์ ๋ง๋ค์ด์คฌ๋ค.
์ด์ ๋์ด๋๊ฐ ์์ ๋ชฌ์คํฐ๋ถํฐ top์์ ๋์ฌํ ๋ฐ ํด๋น ๋ชฌ์คํฐ๋ฅผ ์ก๊ณ ๋ฐ๋ก ์ด ๋ชฌ์คํฐ๋ฅผ ์ก์ผ๋ฉด ๋์ด๋ ๊ฐ์ ํจ๊ณผ๋ฅผ ๋๋ฆด ์ ์๋ ๋ชฌ์คํฐ๋ค์ ๋ชจ๋ ์ฐพ์์ ํํฅ์์ผ์ค๋ค.
ํํฅ ์ํค๊ณ ๋์ ๋ค์ ํ์ ๋ฃ์ด์ค๋ค. ์ด์ฐจํผ ์์ ์๋ ๊ฐ์ ๋ชฌ์คํฐ๋ฅผ ๊ฐฑ์ ์ํค์ง ์์๋ ๋๋ ์ด์ ๋ min heap ์ด๊ณ , ๋์ด๋๊ฐ ๋ด๋ ค๊ฐ๊ธฐ ๋๋ฌธ์ ๊ฐฑ์ ํ ํ์ ์์ด ํ์ ๋ค์ด๊ฐ ๋ชฌ์คํฐ๊ฐ ๋ top์ ๊ฐ๊น์ธ ๊ฒ์ด๋ค.
์ด ๊ณผ์ ์์ visit ๋ฐฐ์ด์ ์ญํ ์ด ์ค์ํ๋ค.
์ฒ์์ queue์์ ๋์ค๋ ๋ชฌ์คํฐ๋ง visit ํ๋ณ์ ํด์คฌ๋๋ ๊ณ์ํด์ TLE๊ฐ ๋ฐ์ํ๋ค.
๊ณฐ๊ณฐํ ์๊ฐํด๋ณด๋ ์ด๋ฏธ ์ฃฝ์ ๋ชฌ์คํฐ๋ ๋์ค์ ์ด๋ค ์์ดํ ์ด ์๊ฒผ๋ค๊ณ ํด์ ๋์ด๋๋ฅผ ํํฅ์์ผ์ค ํ์๊ฐ ์๋ค.
์ด๊ฒ key point ๊ฐ๋ค. ๋ฐ๋ผ์ for ๋ฌธ์์ ์ด๋ฏธ ์ฃฝ์ ๋ชฌ์คํฐ๋ ๋์ด๋ ์ฐ์ฐ ์์ด continue ํ๋๋ก ์์ ํ์๋๋ AC๋ฅผ ๋ฐ์ ์ ์์๋ค.
์ฃผ์ํ ์ ์ ๋ฑ ๋ณด๋ค ์ถ์ด ๋์ด๋๊ฐ ๊ต์ฅํ ํฐ ์ซ์๋ก ๋ค์ด์จ๋ค.
+, - ์ฐ์ฐ์ด ์์ผ๋ ์๋ฃํ์ long long์ผ๋ก ํด์ฃผ์.
๐ป ์ฝ๋
//TLE
//BOJ 20666 ์ธ๋ฌผ์ด์ ์ ์
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <string>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pii;
priority_queue<pii, vector<pii>, greater<pii>> q;
ll add[101010];
int visit[101010];
vector<pii> item[101010];
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N, M;
ll maxC = 0;
cin >> N >> M;
for(int i=1; i<=N; i++) {
cin >> add[i];
}
int p;
cin >> p;
for(int i=0; i<p; i++) {
int a, b, c;
cin >> a >> b >> c;
add[b] += c;
item[a].push_back({b, c});
}
for(int i=1; i<=N; i++) {
q.push({add[i], i});
}
int cnt = 0;
while(cnt < M) {
pii monster = q.top();
q.pop();
if(visit[monster.second]) continue;
visit[monster.second] = 1;
for (pii temp : item[monster.second]) {
if(visit[temp.first]) continue;
add[temp.first] -= temp.second;
q.push({add[temp.first], temp.first});
}
if(maxC < monster.first) maxC = monster.first;
cnt += 1;
}
cout << maxC;
return 0;
}
'DEV > PS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ/14746] Closest Pair, c++ (0) | 2021.09.20 |
---|---|
[BOJ/20218] Parity Constraint Shortest Path, c++ (1) | 2021.08.28 |
[BOJ/20665] ๋ ์์ค ๊ฑฐ๋ฆฌ๋๊ธฐ, c++ (2) | 2021.08.20 |
[BOJ/11280] 2-SAT - 3, c++ (2) | 2021.08.19 |
[BOJ/17222] ์์คํค ๊ฑฐ๋, c++ (2) | 2021.08.12 |