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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
| //Prim
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;
template<typename T>
void Swap(T& a,T& b){T t=a;a=b;b=t;}
template<typename T>
void read(T& w)
{
char r;
for(r=getchar();r<48||r>57;r=getchar());
for(w=0;r>=48&&r<=57;r=getchar())w=w*10+r-48;
}
const int maxn=103;
const int maxm=maxn*(maxn-1)/2;
int n,m;
struct EDGE
{
int to,nxt,w;
void init(int too,int nxtt,int ww)
{
to=too,nxt=nxtt,w=ww;
}
}edge[maxm<<1];
int ek=0;
int node[maxn];
void addEdge(int from,int too,int ww)
{
edge[++ek].init(too,node[from],ww);
node[from]=ek;
}
void input()
{
read(n),read(m);
int x,y,l;
for(int i=1;i<=m;++i)
{
read(x),read(y),read(l);
if(x!=y)
{
addEdge(x,y,l);
addEdge(y,x,l);
}
}
}
bool operator<(const EDGE& a,const EDGE& b)
{
return a.w<b.w;
}
template<typename T>
struct HEAP
{
T ary[maxm<<1];
int f;
HEAP(){f=0;}
void clear(){f=0;}
bool empty(){return f==0;}
void push(const T& w)
{
ary[++f]=w;
for(int k=f;k!=1&&ary[k]<ary[k/2];k=k/2)
{
Swap(ary[k],ary[k/2]);
}
}
T top(){return ary[1];}
T pop()
{
T tmp=ary[1];
ary[1]=ary[f--];
for(int k=1,son=k*2;son<=f;k=son,son=k*2)
{
if(son+1<=f&&ary[son+1]<ary[son])
son=son+1;
if(ary[son]<ary[k])
Swap(ary[son],ary[k]);
else break;
}
return tmp;
}
};
int s=1;
bool vis[maxn];
HEAP<EDGE> h;
int Prim()
{
int sum=0;
for(int k=2,ff=1;k<=n;++k)
{
vis[ff]=true;
for(int i=node[ff];i;i=edge[i].nxt)
{
int v=edge[i].to;
if(!vis[v])
h.push(edge[i]);
}
EDGE tmp;
for(tmp=h.pop();vis[tmp.to];tmp=h.pop());
ff=tmp.to;
sum+=tmp.w;
}
return sum;
}
int main()
{
input();
printf("%d\n",Prim());
return 0;
}
|