poj 2387——单源最短路权值大于0

因为之前做过这个题。所以这次知道这道题有重边。这次dijkstra的写法加入了优先队列的优化

优先队列 结构体从小到大顺序的两种重载运算符的方式

1 bool operator <(const Time& a,const Time& b){
2     return a.start > b.start;
3 }  //这里以大于重载小于是因为默认情况下,优先队列是以大的作为队首,这样一反,就可以再默认情况下使得小的作为队首
1 struct Time{  
2     int start, end;  
3     bool operator < (const Time& t)const{  
4         return start > t.start;  
5     }  
6 };  

对于从大到小结构体重载运算符的方式照上例

 1 #include <iostream>
 2 #include <cstring>
 3 #include <string>
 4 #include <map>
 5 #include <set>
 6 #include <algorithm>
 7 #include <fstream>
 8 #include <cstdio>
 9 #include <cmath>
10 #include <stack>
11 #include <queue>
12 #define lson l,m,rt<<1
13 #define rson m+1,r,rt<<1|1
14 using namespace std;
15 const double Pi=3.14159265358979323846;
16 typedef long long ll;
17 const int MAXN=1000+5;
18 const int dx[4]={0,0,1,-1};
19 const int dy[4]={1,-1,0,0};
20 const int INF = 0x3f3f3f3f;
21 const int NINF = 0xc0c0c0c0;
22 const ll mod=1e9+7;
23 struct qnode{
24     int to,d;
25     bool operator <(const qnode &r)const{
26         return d>r.d;
27     }
28     //运算符的重载 
29 };
30 struct Graph {
31     int weight;
32     int arcs[MAXN][MAXN];
33 }G;
34 int dis[MAXN];
35 void dijkstra(int v,int n)
36 {
37     
38     int U[MAXN];
39     priority_queue <qnode> Q;
40     for(int i=1;i<=n;i++)
41     {
42         U[i]=0;
43     }
44     for(int i=1;i<=n;i++)
45     {
46         dis[i]=INF;
47     }
48     dis[v]=0;
49     qnode tmp;
50     tmp.to=v;tmp.d=0;
51     Q.push(tmp);
52     //这样的没法用优先队列优化,因为没有保留to的值,必须保留才行
53 
54     while(!Q.empty())
55     {
56     
57         tmp=Q.top();Q.pop();
58         int u=tmp.to;
59         if(U[u]) continue;
60         U[u]=1;
61         for(int i=1;i<=n;i++)
62         {
63             if(U[i]==0&&G.arcs[u][i]>0&&dis[i]>dis[u]+G.arcs[u][i])
64             {
65                 dis[i]=dis[u]+G.arcs[u][i];
66                 tmp.d=dis[i];tmp.to=i;
67                 Q.push(tmp);
68             }
69         }
70         
71     }
72      
73     
74 }
75 
76 int main()
77 {
78     int n,t;scanf("%d%d",&t,&n);
79     for(int i=1;i<=t;i++)
80     {
81         int a,b,c;
82         scanf("%d%d%d",&a,&b,&c);
83         if(G.arcs[a][b]!=0&&c>G.arcs[a][b])
84             continue;
85         else
86         {
87             G.arcs[a][b]=c;
88             G.arcs[b][a]=c;
89         }
90     }
91     dijkstra(n,n);
92     int ans=dis[1];
93     cout <<ans<<endl;
94     return 0;
95 }
View Code

加油!加油!加油!

猜你喜欢

转载自www.cnblogs.com/Msmw/p/10541964.html
今日推荐