-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathSPOJ15560.cc
80 lines (72 loc) · 1.55 KB
/
SPOJ15560.cc
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
76
77
78
79
80
// SPOJ 15560: Help the old King
// http://www.spoj.com/problems/IITKWPCG/
//
// Solution: minimum spanning tree
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <queue>
#include <cstring>
#include <functional>
#include <algorithm>
using namespace std;
#define ALL(c) c.begin(), c.end()
#define FOR(i,c) for(typeof(c.begin())i=c.begin();i!=c.end();++i)
#define REP(i,n) for(int i=0;i<n;++i)
#define fst first
#define snd second
typedef long long LL;
struct Edge {
int src, dst, weight;
Edge(int src, int dst, int weight) :
src(src), dst(dst), weight(weight) { }
};
bool operator < (Edge e, Edge f) {
return e.weight > f.weight;
}
struct Graph {
int n;
vector< vector<Edge> > adj;
Graph(int n) : n(n), adj(n) { }
void addEdge(int u, int v, int w) {
adj[u].push_back( Edge(u, v, w) );
adj[v].push_back( Edge(v, u, w) );
}
int minimumSpanningTree() {
int cost = 0;
vector<int> connected(n);
priority_queue<Edge> Q;
Q.push(Edge(-1, 0, 0));
while (!Q.empty()) {
int u = Q.top().dst;
int w = Q.top().weight;
Q.pop();
if (connected[u]++) continue;
cost += w;
FOR(e, adj[u]) Q.push(*e);
}
return cost;
}
};
void doit() {
int n, m;
scanf("%d %d", &n, &m);
Graph G(n);
REP(i, m) {
int u, v;
LL c;
scanf("%d %d %lld", &u, &v, &c);
int e = 0;
while (c > 1) {
c /= 2;
++e;
}
G.addEdge(u-1, v-1, e);
}
printf("%d\n", G.minimumSpanningTree()+1);
}
int main() {
int T; scanf("%d", &T);
while (T--) doit();
}