https://programmers.co.kr/learn/courses/30/lessons/42861
#include <string>
#include <vector>
using namespace std;
int solution(int n, vector<vector<int>> costs) {
int answer = 0;
// 모든 섬을 건널 수 있는 최소 값 길 찾으라
// 다익스트라
vector<int> dij(n, 987654321);
vector<vector<pair<int, int>>> node(n);
for(int i=0;i<costs.size();i++){
node[costs[i][0]].push_back(make_pair(costs[i][1], costs[i][2]));
node[costs[i][1]].push_back(make_pair(costs[i][0], costs[i][2]));
}
dij[0] = -1;
for(int i=0;i<node[0].size();i++){
dij[node[0][i].first] = node[0][i].second;
}
for(int i=0;i<n-1;i++){
int minN;
int mini = 987654320;
for(int j=0;j<n;j++){
if(dij[j] == -1)
continue;
if(mini > dij[j]){
minN = j;
mini = dij[j];
}
}
answer += dij[minN];
for(int j=0;j<node[minN].size();j++){
dij[node[minN][j].first] = min(dij[node[minN][j].first], node[minN][j].second);
}
dij[minN] = -1;
}
return answer;
}
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int d[101];
int getParent(int node){
if(node == d[node]){
return node;
}
else return d[node] = getParent(d[node]);
}
bool compare(vector<int> a, vector<int> b){
return a[2] < b[2];
}
int solution(int n, vector<vector<int>> costs) {
int answer = 0;
for(int i =0; i<n; i++){
d[i] = i;
}
sort(costs.begin(), costs.end(), compare);
for(int i=0; i<costs.size(); i++){
int start = getParent(costs[i][0]);
int end = getParent(costs[i][1]);
int cost = costs[i][2];
if(start != end){
d[end] = start;
answer += cost;
}
}
return answer;
}