Optimized heap prim

Now more and appreciate the fact many things are mastery, as I only know dij can be used to optimize the heap before, but do not know prim can, too, the general idea is the same, is dis record from the known point to the unknown point the shortest distance, so long as each time with v [i] comparison on it, attached to each pick point enumeration of a point, will be much faster pair of QwQ

 1 #include<iostream>
 2 #include<queue>
 3 #include<string.h>
 4 #define N 1100
 5 using namespace std;
 6 int n,m;
 7 
 8 int tot=0,first[N],to[N],v[N],nex[N],vis[N],dis[N];
 9 void add(int x,int y,int z)
10 {
11     tot++;
12     nex[tot]=first[x];
13     first[x]=tot;
14     to[tot]=y;
15     v[tot]=z;
16 }
17 
18 struct node
19 {
20     int dis,num;
21     bool operator< (const node &x)const
22     {
23         x.dis<dis;
24     }
25 };
26 priority_queue<node>q;
27 
28 int main()
29 {
30     memset(dis,0x2f,sizeof(dis));
31     int x,y,z;
32     cin>>n>>m;
33     for(int i=1;i<=m;i++)
34     {
35         cin>>x>>y>>z;
36         add(x,y,z);
37         add(y,x,z);
38     }
39     int ans=0;
40     dis[1]=0;
41     q.push((node){0,1});
42     while(!q.empty())
43     {
44         node now=q.top();
45         q.pop();
46         int x=now.num;
47         if(vis[x])continue;
48         vis[x]=1;
49         ans+=now.dis;
50         for(int i=first[x];i;i=nex[i])
51         {
52             int y=to[i];
53             if(dis[y]>v[i])
54             {
55                 dis[y]=v[i];
56                 q.push((node){dis[y],y});
57              }
 58          }
 59      }
 60      cout << years;
61      return  0 ;
62 }
prim

Oh yeah, also recently learned overloaded operators, is probably the code as written, not deep research, the other has yet to be explored, less than estimated before retiring to explore Liao hopes for a happy retirement, csp refueling !

 

Add a little off topic, by the recent crazy race simulation will find that, in fact, a lot of points are simulations, a lot of things are not just eye clinics not to heart, so the algorithm can not rote, in fact, once you understand the things can be simulated, the code may amount more, nothing's pair of.

 

Guess you like

Origin www.cnblogs.com/S-Gloria/p/11853041.html