Codeforces 938D Buy a Ticket

 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 }

 

posted @ 2018-03-02 20:14  Schenker  阅读(211)  评论(0编辑  收藏  举报