标签:
题目大意:有N个农房,它们之间一共有M条路,求最大生成树
1 #include<iostream> 2 #include<cstring> 3 #include<algorithm> 4 #include<vector> 5 #include<queue> 6 #include<functional> 7 using namespace std; 8 #define MAX_V 6565 9 10 struct edge 11 { 12 int to,cost; 13 edge(int to,int cost) 14 { 15 this->to=to; 16 this->cost=cost; 17 } 18 }; 19 typedef pair<int ,int >P; 20 vector<edge>G[MAX_V]; 21 int maxcost[MAX_V]; 22 bool used[MAX_V]; 23 int V,M; 24 25 int prim() 26 { 27 int res=0; 28 //求解最大生成树要注意元素是从大到小取出的 29 priority_queue<P>que; 30 memset(used,0,V*sizeof(bool)); 31 memset(maxcost,0,sizeof(int)*MAX_V); 32 maxcost[0]=0; 33 que.push(P(0,0)); 34 while(!que.empty()) 35 { 36 P p=que.top(); 37 que.pop(); 38 int v=p.second; 39 if(maxcost[v]>p.first || used[v]) 40 { 41 continue; 42 } 43 used[v]=true; 44 res+=maxcost[v]; 45 for(int i=0;i<G[v].size();i++) 46 { 47 edge e=G[v][i]; 48 if(maxcost[e.to]<e.cost) 49 { 50 maxcost[e.to]=e.cost; 51 que.push(P(maxcost[e.to],e.to)); 52 } 53 } 54 } 55 return res; 56 } 57 58 bool connect() 59 { 60 for(int i=0;i<V;i++) 61 { 62 if(used[i]==0) 63 { 64 return false; 65 } 66 } 67 return true; 68 } 69 70 int main() 71 { 72 cin>>V>>M; 73 while(M--) 74 { 75 int A,B,T; 76 cin>>A>>B>>T; 77 A--; 78 B--; 79 G[A].push_back(edge(B,T)); 80 G[B].push_back(edge(A,T)); 81 } 82 int ans=prim(); 83 if(connect()) 84 { 85 cout<<ans<<endl; 86 } 87 else 88 { 89 cout<<-1<<endl; 90 } 91 return 0; 92 }
标签:
原文地址:http://www.cnblogs.com/xlsryj/p/4916583.html