-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1029.cpp
75 lines (75 loc) · 1.75 KB
/
1029.cpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <vector>
using namespace std;
// ³£¹æµÄËã·¨
int main()
{
int T;
cin >> T;
for (int i = 0;i < T;i++)
{
int n, E;
int mark[501] = {};
int graph[501][501] = {};
vector<int> nodes(0);
int result = 0;
cin >> n >> E;
for (int j = 1;j <= n;j++)
{
for (int k = 1;k <= n;k++)
{
if (j == k);
else
{
graph[j][k] = INT32_MAX;
}
}
}
for (int j = 0;j < E;j++)
{
int u, v, w;
cin >> u >> v >> w;
if (graph[u][v] > w)
{
graph[u][v] = w;
graph[v][u] = graph[u][v];
}
}
nodes.push_back(1);
mark[1] = 1;
while (1)
{
int minedge = INT32_MAX;
int minvertex = 0;
for (int j = 0;j < nodes.size();j++)
{
for (int k = 1;k <= n;k++)
{
if (!mark[k] && graph[nodes[j]][k] < minedge)
{
minvertex = k;
minedge = graph[nodes[j]][k];
}
}
}
if (minvertex)
{
nodes.push_back(minvertex);
result += minedge;
mark[minvertex] = 1;
}
else
{
break;
}
}
if (nodes.size() == n)
{
cout << result << endl;
}
else
{
cout << -1 << endl;
}
}
}