C
#include <stdio.h>
#include <string.h>
#define MAXSIZE 510
#define INF 0x3f3f3f3f
#define min(a,b) ((a)<(b)?(a):(b))
int n, m, visited[MAXSIZE], dist[MAXSIZE], graph[MAXSIZE][MAXSIZE];
void init() {
scanf("%d%d", &n, &m);
memset(dist, 0x3f, sizeof(dist));
memset(graph, 0x3f, sizeof(graph));
for (int i = 1; i <= n; ++i) {
graph[i][i] = 0;
}
int u, v, w;
while (m--) {
scanf("%d%d%d", &u, &v, &w);
graph[u][v] = min(graph[u][v], w);
graph[v][u] = min(graph[v][u], w);
}
}
int Prim() {
dist[1] = 0;
int ans = 0;
for (int i = 1; i <= n; ++i) {
int u = -1, curMin = INF;
for (int j = 1; j <= n; ++j) {
if (!visited[j] && dist[j] < curMin) {
u = j;
curMin = dist[j];
}
}
if (u == -1) {
return -1;
}
visited[u] = 1;
ans += dist[u];
for (int v = 1; v <= n; ++v) {
if (!visited[v] && graph[u][v] != INF) {
dist[v] = min(dist[v], graph[u][v]);
}
}
}
return ans;
}
int main() {
init();
int res = Prim();
if (res == -1) {
puts("impossible");
} else {
printf("%d\n", res);
}
return 0;
}
C++
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
const int MAXSIZE = 510;
const int INF = 0x3f3f3f3f;
int n, m;
vector<bool> visited(MAXSIZE, false);
vector<int> dist(MAXSIZE, INF);
vector<vector<int> > graph(MAXSIZE, vector<int>(MAXSIZE, INF));
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
void init() {
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
graph[i][i] = 0;
}
int u, v, w;
while (m--) {
cin >> u >> v >> w;
graph[u][v] = min(graph[u][v], w);
graph[v][u] = min(graph[v][u], w);
}
}
int Prim() {
dist[1] = 0;
int ans = 0, cnt = 0;
pq.emplace(dist[1], 1);
while (!pq.empty()) {
auto [d, u] = pq.top();
pq.pop();
if (visited[u]) {
continue;
}
visited[u] = true;
++cnt;
ans += d;
for (int v = 1; v <= n; ++v) {
if (!visited[v] && graph[u][v] != INF && graph[u][v] < dist[v]) {
dist[v] = graph[u][v];
pq.emplace(dist[v], v);
}
}
}
return cnt == n ? ans : -1;
}
int main() {
init();
if (int res = Prim(); res == -1) {
cout << "impossible" << endl;
} else {
cout << res << endl;
}
return 0;
}