镖局的运镖,就是运货(类似现在的物流)。镖局每到一个新地方开展业务,都需要对运镖途中的绿林好汉进行打点。好说话的打点费就比较低,不好说话的打点费就比较高。龙门镖局现在有一趟镖请你来规划路线,已知城市的地图,你需要选择一些道路进行疏通,以便镖局可以到达任意一个城市,要求花费的银子越少越好。
输入格式:
第一行有两个数n和m,n表示有n个城市(编号从1到n),m表示有m条道路。接下来m行,每行形如“a b c”用来表示一条道路,意思是城市a到城市b连通且打点需要花费的银子数是c。
输出格式:
若通过打点能抵达所有城市,则输出最少需要花费的银子总数。若不能抵达所有的城市则输出“impossible”。
输入样例:
3 3
1 2 1
1 3 2
2 3 4
输出样例:
3
最小生成树 kruscal
#define debug
#ifdef debug
#include <time.h>
#include "/home/majiao/mb.h"
#endif
#include <iostream>
#include <algorithm>
#include <vector>
#include <string.h>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <math.h>
#define MAXN ((int)2e6+7)
#define ll long long
#define INF (0x7f7f7f7f)
#define fori(lef, rig) for(int i=lef; i<=rig; i++)
#define forj(lef, rig) for(int j=lef; j<=rig; j++)
#define fork(lef, rig) for(int k=lef; k<=rig; k++)
#define QAQ (0)
using namespace std;
#define show(x...) \
do { \
cout << "\033[31;1m " << #x << " -> "; \
err(x); \
} while (0)
void err() { cout << "\033[39;0m" << endl; }
template<typename T, typename... A>
void err(T a, A... x) { cout << a << ' '; err(x...); }
namespace FastIO {
char print_f[105];
void read() { }
void print() { putchar('\n'); }
template <typename T, typename... T2>
inline void read(T &x, T2 &... oth) {
x = 0;
char ch = getchar();
ll f = 1;
while (!isdigit(ch)) {
if (ch == '-') f *= -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
x *= f;
read(oth...);
}
template <typename T, typename... T2>
inline void print(T x, T2... oth) {
ll p3=-1;
if(x<0) putchar('-'), x=-x;
do{
print_f[++p3] = x%10 + 48;
} while(x/=10);
while(p3>=0) putchar(print_f[p3--]);
// putchar(' ');
print(oth...);
}
} // namespace FastIO
using FastIO::print;
using FastIO::read;
int n, m, Q, K;
struct Edge {
int u, v, w;
bool operator < (const Edge& no) const {
return w < no.w;
}
} ed[MAXN];
vector<Edge> G[MAXN];
int pre[MAXN];
int fa(int x) {
return x == pre[x] ? x : (pre[x] = fa(pre[x]));
}
void union_xy(int x, int y) {
x = fa(x), y = fa(y);
if(x != y) {
pre[y] = x;
}
}
void init() {
for(int i=1; i<=n; i++) pre[i] = i;
}
void krs() {
K = n - 1;
init();
int sum = 0;
sort(ed+1, ed+1+m);
for(int i=1; i<=m && K; i++) {
if(fa(ed[i].u) == fa(ed[i].v)) continue ;
union_xy(ed[i].u, ed[i].v);
sum += ed[i].w;
K --;
}
if(K) printf("impossible");
else printf("%d\n", sum);
}
int main() {
#ifdef debug
freopen("test", "r", stdin);
// freopen("out_main", "w", stdout);
clock_t stime = clock();
#endif
read(n, m);
for(int M = m; M; M--)
read(ed[M].u, ed[M].v, ed[M].w);
krs();
#ifdef debug
clock_t etime = clock();
printf("rum time: %lf 秒\n",(double) (etime-stime)/CLOCKS_PER_SEC);
#endif
return 0;
}