POJ 2377
2015-10-28 10:39
405 查看
POJ 2377
题目大意:有N个农房,它们之间一共有M条路,求最大生成树
题目大意:有N个农房,它们之间一共有M条路,求最大生成树
#include<iostream> #include<cstring> #include<algorithm> #include<vector> #include<queue> #include<functional> using namespace std; #define MAX_V 6565 struct edge { int to,cost; edge(int to,int cost) { this->to=to; this->cost=cost; } }; typedef pair<int ,int >P; vector<edge>G[MAX_V]; int maxcost[MAX_V]; bool used[MAX_V]; int V,M; int prim() { int res=0; //求解最大生成树要注意元素是从大到小取出的 priority_queue<P>que; memset(used,0,V*sizeof(bool)); memset(maxcost,0,sizeof(int)*MAX_V); maxcost[0]=0; que.push(P(0,0)); while(!que.empty()) { P p=que.top(); que.pop(); int v=p.second; if(maxcost[v]>p.first || used[v]) { continue; } used[v]=true; res+=maxcost[v]; for(int i=0;i<G[v].size();i++) { edge e=G[v][i]; if(maxcost[e.to]<e.cost) { maxcost[e.to]=e.cost; que.push(P(maxcost[e.to],e.to)); } } } return res; } bool connect() { for(int i=0;i<V;i++) { if(used[i]==0) { return false; } } return true; } int main() { cin>>V>>M; while(M--) { int A,B,T; cin>>A>>B>>T; A--; B--; G[A].push_back(edge(B,T)); G[B].push_back(edge(A,T)); } int ans=prim(); if(connect()) { cout<<ans<<endl; } else { cout<<-1<<endl; } return 0; }
相关文章推荐
- 【足迹C++primer】49、超载,更改,运营商
- 判断输入的是否是大于0的正整数
- Linux下Wireshark的网络抓包使用方法
- C++【类与访控属性】
- 电源中磁珠作用分析
- Hive参数配置以及HQL编写技巧
- JAVA中的final关键字
- java的System.getProperty()方法可以获取的值
- 贪心
- Unity:镜面反射
- 关于支付的几点注意
- mysql输出的错误提示是法语
- matlab程序移植到C(输出比较)
- 输出1000-2000是闰年的年份
- TBS调试手机QQ浏览器
- 【Qt多线程之信号量】Qsemaphore
- 第七讲流程图
- 解决maven与eclipse中@override出现must override a superclass method错误
- python文件的整体结构
- LeetCode Serialize and Deserialize Binary Tree