[ ๋ฌธ์ ๋งํฌ ]
https://www.acmicpc.net/problem/16398
๐ฉ ์กฐ๊ฑด
- ์ ๊ตญ ๋ด ๋ชจ๋ ํ์ฑ์ ์ฐ๊ฒฐ
- ๊ทธ ์ ์ง๋น์ฉ์ ์ต์ํ
๐ฉ ์ ๊ทผ
1,2 -> ์ต์์ ์ฅํธ๋ฆฌ => Prim ์๊ณ ๋ฆฌ์ฆ์ ์ด์ฉํ์!
๐ฉ ์ํ์ฐฉ์ค
ํ๋ก์ฐ ๊ด๋ฆฌ ๋น์ฉ์ ๋ฒ์๊ฐ "1 ≤ Cij ≤ 100,000,000"์ด๋ฏ๋ก, ์ฒ์์ ans๋ฅผ int๋ก ์ ์ธํ์ฌ "ํ๋ ธ์ต๋๋ค"๊ฐ ๋์ด
=> ans๋ฅผ long long์ผ๋ก ์ ์ธํ์ฌ์ผ ํจ
๐ป ์ฝ๋ (C++)
#include <iostream>
#include <queue>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;
priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> pq; //cost, a, b
vector<pair<int, int>> adj[1001]; //cost, b
bool check[1001];
int main() {
int N, c;
int a, b;
cin >> N;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
cin >> c;
if (c == 0)continue;
adj[i].push_back({ c,j });
}
}
//์ฒซ ๋ฐฉ๋ฌธ : 0๋ฒ ํ์ฑ
int cnt = 1;
long long ans = 0;
a = 0; check[a] = true;
while (cnt <= N - 1) {
for (auto next : adj[a]) {
pq.push({ next.first, a, next.second });
}
tie(c, a, b) = pq.top();
while (check[b]) {
pq.pop();
tie(c, a, b) = pq.top();
}
ans += c;
check[b] = true;
a = b;
pq.pop();
cnt++;
}
cout << ans;
}
'๐ป Algorithms > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 11403 ๊ฒฝ๋ก ์ฐพ๊ธฐ - ๊ทธ๋ํ, DFS (0) | 2024.08.17 |
---|---|
[๋ฐฑ์ค] 1927 ์ต์ ํ - ์ฐ์ ์์ ํ (0) | 2024.08.14 |
[๋ฐฑ์ค] 11780 ํ๋ก์ด๋2 - ํ๋ก์ด๋ ๊ฒฝ๋ก๋ณต์ (0) | 2024.08.04 |
[๋ฐฑ์ค] 11404 ํ๋ก์ด๋ - ํ๋ก์ด๋ (0) | 2024.08.04 |
[๋ฐฑ์ค] 1766 ๋ฌธ์ ์ง - ์์์ ๋ ฌ, ์ฐ์ ์์ ํ (0) | 2024.08.04 |