现在越来越体会到其实很多东西都是融会贯通的,就像我之前只知道dij可以用堆优化,却不知道prim也可以一样,大体思路还是不变,就是dis记录从已知点到未知点的最短距离,于是每次只要跟v[i]作比较就可以了,每次挑一个点枚举连着的点,会快很多的叭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<<ans; 61 return 0; 62 }
哦对,近期还学会了重载运算符,大概就是代码中写的那样,研究的并不深,其他的还有待探索,估计退役之前是探索不到辽,希望有一个美满的退役,csp加油!
加一点点题外话,通过近期疯狂的模拟赛会发现,其实很多分都是模拟来的,很多不会的东西只是目光所及心未必至,因此算法不能死记硬背,其实只要理解了的东西都是可以模拟出来的,可能码量多点,也没什么的叭。