-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrim.cpp
More file actions
62 lines (39 loc) · 1002 Bytes
/
Copy pathPrim.cpp
File metadata and controls
62 lines (39 loc) · 1002 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> pii;
const int N = 10000;
const int INF = 99999999;
int A[N][N] , distancia[N] , vis[N] , n; // n = numero de nos
priority_queue< pii , vector<pii> , greater<pii> > D;
void Prim(int x){
for(int i = 1 ; i <= n ; i++) distancia[i] = INF;
distancia[x] = 0;
D.push(make_pair(0,x));
while(!D.empty()){
pii a = D.top();
D.pop();
if(vis[a.second] == 1) continue;
vis[a.second] = 1;
for(int i = 1 ; i <= n ; i++){
if(distancia[i] > A[i][a.second]){
distancia[i] = A[i][a.second];
D.push(make_pair(distancia[i],i));
}
}
}
}
int main(){
int q;
cin >> n >> q;
for(int i = 0 ; i < N ; i++)
for(int j = 0 ; j < N ; j++) A[i][j] = INF;
for(int i = 0 ; i < q ; i++){
int x , y , z;
cin >> x >> y >> z;
A[x][y] = z;
A[y][x] = z;
}
Prim(1);
for(int i = 1 ; i <= n ; i++) cout << distancia[i] << " ";
return 0;
}