HDU 1009 The Shortest Path in Nya Graph
迪杰斯特拉 + 优先队列
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cmath> 6 #include <queue> 7 #include <vector> 8 9 #define LL __int64 10 11 const LL INF = 2000000000; 12 13 using namespace std; 14 15 LL dis[300100]; 16 17 int head[300100]; 18 19 struct E 20 { 21 int u,v,w,next; 22 }edge[1001000]; 23 24 int top; 25 26 void link(int u,int v,int w) 27 { 28 edge[top].u = u; 29 edge[top].v = v; 30 edge[top].w = w; 31 edge[top].next = head[u]; 32 head[u] = top++; 33 } 34 35 struct HeapNode 36 { 37 int d,u; 38 bool operator < (const HeapNode& rhs) const{ 39 return d>rhs.d; 40 } 41 }; 42 43 void dij(int st,int n) 44 { 45 priority_queue<HeapNode> q; 46 47 HeapNode p; 48 49 p.d = 0; 50 p.u = 1; 51 52 q.push(p); 53 54 while(q.empty() == false) 55 { 56 HeapNode x = q.top(); 57 q.pop(); 58 59 int u = x.u; 60 61 st = head[u]; 62 63 while(st != -1) 64 { 65 if(dis[u] + edge[st].w < dis[edge[st].v]) 66 { 67 dis[edge[st].v] = edge[st].w + dis[u]; 68 69 HeapNode temp; 70 71 temp.d = dis[edge[st].v]; 72 temp.u = edge[st].v; 73 q.push(temp); 74 } 75 st = edge[st].next; 76 77 } 78 } 79 80 if(dis[n] == INF) 81 cout<<"-1"<<endl; 82 else 83 cout<<dis[n]<<endl; 84 } 85 86 int main() 87 { 88 int i,n,m,c,u,v,w; 89 int T,icase = 0; 90 91 cin>>T; 92 while(T--) 93 { 94 scanf("%d %d %d",&n,&m,&c); 95 96 memset(head,-1,(n*3+2)*sizeof(int)); 97 98 top = 0; 99 100 for(i = 1;i <= n; ++i) 101 { 102 scanf("%d",&u); 103 104 link(n+2*u-1,i,0); 105 link(i,n+u*2,0); 106 } 107 108 for(i = 1;i < n; ++i) 109 { 110 link(n+i*2+2,n+i*2-1,c); 111 link(n+i*2,n+i*2+1,c); 112 } 113 114 for(i = 1;i <= m; ++i) 115 { 116 scanf("%d %d %d",&u,&v,&w); 117 link(u,v,w); 118 link(v,u,w); 119 } 120 121 for(i = 1,n *= 3;i <= n; ++i) 122 { 123 dis[i] = INF; 124 } 125 126 dis[1] = 0; 127 128 printf("Case #%d: ",++icase); 129 dij(1,n/3); 130 131 } 132 return 0; 133 }
墨迹了一下午 效率低了一13