Luo Gu p3366prim + + heap Optimization adjacency lists

This board is a problem, people suitable for beginners to practice hand the minimum spanning tree
Click here to view the topic (https://www.luogu.org/problemnew/show/P3366)
Of course, such as the title, there is only prim code
Note:
1.prim with adjacency lists exist side should pay attention to the size of the array with no problems edges
2. the default priority queue ordered according to a first keyword ranking
3. fast input may be required to optimize the read data is too large
4. the line code has been pressed, use caution
5. All are welcome dalao pointed out this error of konjac
offer Code:

#include<bits/stdc++.h> 
using namespace std;
typedef pair <int,int> pii;
priority_queue <pii,vector<pii>,greater<pii> > q;
struct node{int to,val,next;}e[400010];
int vis[400010],n,m,ans,u=1,k,head[400010],mi,cnt;
void add(int x,int y,int z){e[++k].to=y,e[k].val=z,e[k].next=head[x],head[x]=k;}
inline void read(int &x)
{
    x=0;int f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-f;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0',ch=getchar();}x*=f;
}
int main ()
{
    read(n),read(m);
    for(int i=1;i<=m;i++)
    {
        int a,b,c;
        read(a),read(b),read(c);
        add(a,b,c),add(b,a,c);
    }
    q.push(make_pair(0,1));
    while(!q.empty()&&cnt<=n)
    {    
        int u=q.top().second,v=q.top().first;
        q.pop();
        if(vis[u])continue;
        cnt++,ans+=v,vis[u]=1;
        for(int i=head[u];i!=0;i=e[i].next)
        if(!vis[e[i].to])
        q.push(make_pair(e[i].val,e[i].to));
    }
    cout << years;
    return  0 ;
}

 

Guess you like

Origin www.cnblogs.com/57412626-996842/p/11091230.html