UVA 10801 Dij最短路(改模板)
题意:有n个电梯,目的地是第K层(起点是第0层),给出每个电梯的速度,以及每个电梯能到达的层数,如果中途需要换电梯的话,时间需要+60,求到达目的地的最短时间;
思路:Dij求最短路。如果是另一条路比较短的话,相当于乘别的电梯,也就是再+60,自己不可能和自己比,即d[e.v] 和 d[e.u] + d + 60比较即可;
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <string> 5 #include <sstream> 6 #include <queue> 7 #include <vector> 8 #define repu(i,a,b) for(int i=a;i<b;i++) 9 using namespace std; 10 string s; 11 #define N 110 12 int v[N],t[N]; 13 const int maxn=2200; 14 const int INF=0x3f3f3f3f; 15 int rode[maxn]; 16 int st = 0,ed,k; 17 18 struct Edge 19 { 20 int u, v,d; 21 Edge(int u, int v, int d):u(u), v(v), d(d) {} 22 }; 23 24 struct qnode 25 { 26 int u; 27 int d; 28 qnode(int u, int d):u(u), d(d) {} 29 bool operator < (const qnode a)const 30 { 31 return d > a.d; 32 } 33 }; 34 35 struct Dijkstra 36 { 37 int n; 38 vector<int> G[maxn]; 39 vector<Edge> edge; 40 int d[maxn]; 41 bool vis[maxn]; 42 void init(int n) 43 { 44 this->n=n; 45 for(int i=0; i<=n; i++) 46 { 47 G[i].clear(); 48 vis[i]=0; 49 d[i]=INF; 50 } 51 edge.clear(); 52 } 53 void AddEdge(int u, int v, int d) 54 { 55 G[u].push_back(edge.size()); 56 edge.push_back(Edge(u, v, d)); 57 } 58 int dijkstra(int k) 59 { 60 memset(vis, 0, sizeof vis); 61 priority_queue<qnode> q; 62 d[0]=0; 63 q.push(qnode(0, 0)); 64 while(!q.empty()) 65 { 66 qnode x = q.top(); 67 q.pop(); 68 if(vis[x.u]) 69 continue ; 70 vis[x.u]=true; 71 if(x.u == k) 72 return d[k] - 60; 73 if(d[x.u] == INF) return -1; 74 for(int i=0; i<G[x.u].size(); i++) 75 { 76 Edge e=edge[G[x.u][i]]; 77 int tep = d[e.u] + e.d + 60; 78 if(d[e.v] > tep) 79 { 80 d[e.v] = tep; 81 q.push(qnode(e.v, d[e.v])); 82 } 83 } 84 } 85 return -1; 86 } 87 } dij; 88 89 int main() 90 { 91 int n,k; 92 while(~scanf("%d%d",&n,&k)) 93 { 94 int maxn = 0; 95 memset(v,0,sizeof(v)); 96 st = 0; 97 ed = k; 98 repu(i,0,n) 99 scanf("%d",&v[i]); 100 int m=0; 101 getchar(); 102 dij.init(N); 103 repu(i,0,n) 104 { 105 getline(cin,s); 106 int l = s.length(),last = 0; 107 m = 0; 108 memset(t,0,sizeof(t)); 109 repu(j,0,l) 110 { 111 if(s[j] == ' ') 112 { 113 string c = s.substr(last,j-last); 114 last = j; 115 stringstream ss1(c); 116 ss1 >> t[m]; 117 m++; 118 } 119 } 120 string c = s.substr(last,l-last); 121 stringstream ss1(c); 122 ss1 >> t[m]; 123 m++; 124 125 // repu(j,0,m) 126 // cout<<t[j]<<" "; 127 // cout<<endl; 128 129 repu(j,0,m) 130 repu(p,j+1,m) 131 { 132 dij.AddEdge(t[j], t[p], (t[p]-t[j])*v[i]); 133 dij.AddEdge(t[p], t[j], (t[p]-t[j])*v[i]); 134 } 135 } 136 if(k == 0) 137 { 138 printf("0\n"); 139 continue; 140 } 141 int ans = dij.dijkstra(ed); 142 if(ans == -1) 143 printf("IMPOSSIBLE\n"); 144 else 145 printf("%d\n",ans); 146 } 147 return 0; 148 }
人生就像心电图,想要一帆风顺,除非game-over