1. 程式人生 > 其它 >最小生成樹:洛谷P3366【模板】最小生成樹

最小生成樹:洛谷P3366【模板】最小生成樹

https://www.luogu.com.cn/problem/P3366

Prim演算法/最小生成樹裸題:不斷取出未加入集合的點中距離最近的那個,並將其連的所有邊加入priority_queue中(priority_queue過載運算子<然後用node),反覆迴圈直到priority_queue為空

重點:priority_queue的使用

#include<bits/stdc++.h>
#define INF 2147483647
using namespace std;
int been[5003];
struct node{
    int num,to,value;
};
bool
operator < (const node &a, const node &b){ return a.value > b.value; } int main(){ vector<node>a[5003]; priority_queue<node> q; int n,m,i,x,y,z,ans,ansn; node t;t.value=INF; memset(been,0,sizeof(been)); cin>>n>>m; for(i=1;i<=m;i++){ scanf(
"%d%d%d",&x,&y,&z); node b,c; b.num=x;b.to=y;b.value=z; c.num=y;c.to=x;c.value=z; if(z<t.value) t=b; a[x].push_back(b); a[y].push_back(c); } t.to=t.num;t.value=0;q.push(t); ans=0;ansn=0; while(!q.empty()){ node b=q.top();q.pop();x=b.to;
if(been[x]) continue; ans+=b.value;ansn++; been[x]=true; // printf("%d->%d:%d\n",b.num,b.to,b.value); for(i=0;i<a[x].size();i++){ if(!been[a[x][i].to]) q.push(a[x][i]); } } if(ansn==n) cout<<ans; else cout<<"orz"; }