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
|
#include <cstdio> #include <string> #include <cstring> #include <iostream> #include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 505;
int a[maxn][maxn];
int vis[maxn],dist[maxn];
int n,m;
int u,v,w;
long long sum = 0;
int prim(int pos) { dist[pos] = 0; for(int i = 1; i <= n; i ++) { int cur = -1; for(int j = 1; j <= n; j ++) { if(!vis[j] && (cur == -1 || dist[j] < dist[cur])) { cur = j; } } if(dist[cur] >= INF) return INF; sum += dist[cur]; vis[cur] = 1; for(int k = 1; k <= n; k ++) { if(!vis[k]) dist[k] = min(dist[k],a[cur][k]); } } return sum; }
int main(void) { scanf("%d%d",&n,&m); memset(a,0x3f,sizeof(a)); memset(dist,0x3f,sizeof(dist)); for(int i = 1; i <= m; i ++) { scanf("%d%d%d",&u,&v,&w); a[u][v] = min(a[u][v],w); a[v][u] = min(a[v][u],w); } int value = prim(1); if(value >= INF) puts("impossible"); else printf("%lld\n",sum); return 0; }
|