今天对最小生成树进行了总结上午写了kruscal算法,现在把Prim算法加上队列优化更新一下,多写才能更熟练,打代码有事也能成为一种乐趣哈哈:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF = 0x3f3f3f3f;
struct node{
int id;
int w;
bool operator < (const node & rhs)const
{
return w > rhs.w;//代表把最小权值的边放在队列头。
}
};
vector<node>S[1005];
bool vis[1005];
int main()
{
int n,m,tot = 1,sum = 0;
priority_queue<node>q;
/*while(!q.empty())
{
node e = q.top();
cout << e.id << " " << e.w << endl;
q.pop();
}*/
while(cin >> n >> m)
{
//S.clear();
int a,b,c;
for(int i = 1;i <= m;i++)
{
cin >> a >> b >> c;
S[a].push_back(node{b,c});//这么存图的话一定要记得重载小于号,刚开始写总会犯的·错误。
S[b].push_back(node{a,c});
}
//prim算法。
node now;
now.id = 1;
now.w = 0;
q.push(now);
while(tot <= n && !q.empty())
{
node fr = q.top();
q.pop();
if(vis[fr.id] == 1) continue;
vis[fr.id] = 1;
tot++;
sum += fr.w;
for(int i = 0;i < S[fr.id].size();i++)
{
if(!vis[S[fr.id][i].id]) q.push(S[fr.id][i]);
}
}
cout << sum << endl;
}
}