1. 程式人生 > >Codeforces 938D Buy a Ticket

Codeforces 938D Buy a Ticket

using dijk body const ems 入隊 turn 情況 pop

Buy a Ticket

題意要求:求出每個城市看演出的最小費用, 註意的一點就是車票要來回的。

題解:dijkstra 生成優先隊列的時候直接將在本地城市看演出的費用放入隊列裏, 然後直接跑就好了, dis數組存的是, 當前情況下的最小花費是多少。

代碼:

 1 #include<iostream>
 2 #include<cstring>
 3 #include<string>
 4 #include<queue>
 5 #include<vector>
 6 #include<algorithm>
 7 #include<cmath>
 8
#include<iomanip> 9 #include<cstdio> 10 #define LL long long 11 #define ULL unsigned LL 12 #define lson l,m,rt<<1 13 #define rson m+1,r,rt<<1|1 14 #define fi first 15 #define se second 16 using namespace std; 17 typedef pair<LL, int> pll; 18 const int N = 2e5+5; 19 LL dis[N];
20 int head[N]; 21 struct Node{ 22 int to; 23 int nt; 24 LL ct; 25 }e[N<<1]; 26 priority_queue<pll, vector<pll>, greater<pll> > q; 27 void dijkstra(){ 28 while(!q.empty()){ 29 int u = q.top().se; 30 LL w = q.top().fi; 31 q.pop(); 32 if
(dis[u] != w) continue; 33 for(int i = head[u]; ~i; i = e[i].nt){ 34 int v = e[i].to; 35 if(dis[v] > dis[u] + e[i].ct){ 36 dis[v] = dis[u] + e[i].ct; 37 q.push(pll(dis[v],v)); 38 } 39 } 40 } 41 } 42 int tot = 0; 43 void add(int u, int v, LL w){ 44 e[tot].ct = w; 45 e[tot].to = v; 46 e[tot].nt = head[u]; 47 head[u] = tot++; 48 } 49 int main(){ 50 ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); 51 memset(head, -1, sizeof(head)); 52 int n, m; 53 cin >> n >> m; 54 int u, v; 55 LL ct; 56 for(int i = 1; i <= m; i++){ 57 cin >> u >> v >> ct; 58 add(u,v,ct*2); 59 add(v,u,ct*2); 60 } 61 for(int i = 1; i <= n; i++){ 62 cin >> ct; 63 q.push(pll(ct,i)); 64 dis[i] = ct; 65 } 66 dijkstra(); 67 for(int i = 1; i < n; i++){ 68 cout << dis[i] << ; 69 } 70 cout << dis[n] << endl; 71 return 0; 72 }

Codeforces 938D Buy a Ticket