Prim堆优化

@

目录

    \(d^i_jk^s_tr^a\)一样啦。。。

    #include<cstdio>
    #include<iostream>
    #include<queue>
    using namespace std;
    int read(){
    	int x=0,pos=1;char ch=getchar();
    	for(;!isdigit(ch);ch=getchar()) if(ch=='-') pos=0;
    	for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
    	return pos?x:-x;
    }
    struct node{
    	int v,nex,w;
    }edge[2000001];
    struct pt{
    	int po,d;
    	bool operator < (const pt &a) const{
    		return d>a.d;
    	}
    };
    int top,head[1000001];
    void add(int u,int v,int w){
    	edge[++top].v=v;
    	edge[top].nex=head[u];
    	edge[top].w=w;
    	head[u]=top;
    }
    int n,m;
    queue<pt>q;
    int vis[1000001];
    int main(){
    	n=read(),m=read();
    	for(int i=1;i<=m;i++){
    		int u=read(),v=read(),w=read();
    		add(u,v,w);
    		add(v,u,w);
    	}
    	int ans=0;
    	priority_queue<pt>q;
    	pt fi;
    	fi.po=1;
    	fi.d=0;
    	q.push(fi);
    	int cnt=0;
    	while(!q.empty()){
    		pt now=q.top();q.pop();
    		if(vis[now.po]) continue;
    		cnt++;
    		vis[now.po]=1;
    		ans+=now.d;
    		for(int i=head[now.po];i;i=edge[i].nex){
    			int v=edge[i].v;
    			if(!vis[v]){
    				pt ne;
    				ne.d=edge[i].w;
    				ne.po=v;
    				q.push(ne);
    			}
    		}
    	}
    	if(cnt==n) printf("%d",ans);
    	else printf("orz");
    	return 0;
    }
    
    posted @ 2019-07-27 22:50  lcyfrog  阅读(190)  评论(0编辑  收藏  举报