标签:
最优灌溉
时间限制: | 1.0s |
内存限制: | 256.0MB |
1 #include <bits/stdc++.h> 2 #define LL long long 3 #define INF 0x3f3f3f3f3f3f3f 4 #define pii pair<int,int> 5 using namespace std; 6 const int maxn = 2000; 7 struct arc{ 8 int to,cost,next; 9 arc(int x = 0,int y = 0,int z = -1){ 10 to = x; 11 cost = y; 12 next = z; 13 } 14 }e[500000]; 15 int tot,n,m,head[maxn]; 16 LL d[maxn]; 17 bool done[maxn]; 18 void add(int u,int v,int cost){ 19 e[tot] = arc(v,cost,head[u]); 20 head[u] = tot++; 21 e[tot] = arc(u,cost,head[v]); 22 head[v] = tot++; 23 } 24 priority_queue< pii,vector< pii >,greater< pii > >q; 25 LL prim(){ 26 while(!q.empty()) q.pop(); 27 for(int i = 1; i <= n; ++i){ 28 done[i] = false; 29 d[i] = INF; 30 } 31 q.push(make_pair(d[1] = 0,1)); 32 LL ans = 0; 33 while(!q.empty()){ 34 int u = q.top().second; 35 q.pop(); 36 if(done[u]) continue; 37 done[u] = true; 38 ans += d[u]; 39 for(int i = head[u]; ~i; i = e[i].next){ 40 if(!done[e[i].to] && e[i].cost < d[e[i].to]){ 41 d[e[i].to] = e[i].cost; 42 q.push(make_pair(d[e[i].to],e[i].to)); 43 } 44 } 45 } 46 return ans; 47 } 48 int main(){ 49 int u,v,w; 50 while(~scanf("%d %d",&n,&m)){ 51 memset(head,-1,sizeof(head)); 52 for(int i = tot = 0; i < m; ++i){ 53 scanf("%d %d %d",&u,&v,&w); 54 add(u,v,w); 55 } 56 printf("%I64d\n",prim()); 57 } 58 return 0; 59 }
标签:
原文地址:http://www.cnblogs.com/crackpotisback/p/4355791.html