您的位置:首页 > 其它

POJ 2377

2015-10-28 10:39 405 查看
POJ 2377

题目大意:有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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: