1. 程式人生 > >迪傑斯特拉_優先隊列 模板

迪傑斯特拉_優先隊列 模板

模板 printf emp str end 操作 esp name continue

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 struct node
 4 {
 5     int pos,len;
 6     bool friend operator<(node c,node d)
 7     {
 8         return c.len>d.len;//優先隊列原本是從大到小排列的,這裏把小於號重載為特殊的大於號,使得隊列中的元素從小到大出隊,從而代替循環操作
 9     }
10     /*
11     bool operator<(const node &c)const
12 { 13 return len>c.len; 14 } 15 */ 16 }now,next; 17 priority_queue<node>q; 18 int g[104][104]; 19 int vis[104]; 20 int n,m; 21 void dij() 22 { 23 while(!q.empty()) 24 { 25 now=q.top(); 26 q.pop(); 27 if(now.pos==n) 28 {
29 printf("%d\n",now.len); 30 while(!q.empty()) 31 q.pop(); 32 return; 33 } 34 if(vis[now.pos])continue; 35 vis[now.pos]=1; 36 for(int i=1;i<=n;i++) 37 { 38 if(g[now.pos][i]&&!vis[i])
39 { 40 next.pos=i; 41 next.len=g[now.pos][i]+now.len; 42 q.push(next); 43 } 44 } 45 } 46 } 47 int main() 48 { 49 while(~scanf("%d%d",&n,&m)&&n&&m) 50 { 51 memset(g,-1,sizeof g); 52 for(int i=0;i<m;i++) 53 { 54 int u,v,l; 55 scanf("%d%d%d",&u,&v,&l); 56 if(g[u][v]==-1||l<g[u][v]) 57 g[u][v]=g[v][u]=l; 58 } 59 now.pos=1,now.len=1; 60 q.push(now); 61 dij(); 62 } 63 return 0; 64 }

迪傑斯特拉_優先隊列 模板