codeforces 938D Buy a Ticket 有初值的Dijkstra、有趣的题目
2018-02-19 23:07
471 查看
题意
给出一些城市电影票的价格,以及城市之间交通的路费,询问每一个城市怎样才能花最少的钱看到电影(看完电影还要再回来)。题解
这是一道不太难但是挺有趣的题目。我们这样想,每个城市只需要查看票价比他更便宜的城市,来更新本城市的票价就可以了,是不是想到了Dijkstra求最短路的思路。
这样的话,我们先从票价最便宜的城市开始,从这个城市出发,更新其他所有城市的票价(新票价=原票价+2*路费),然后本城市的票价就求出来了。
再重复上述操作,也就是重新找一个票价最低的城市,然后更新其他城市的票价,这样就ok啦。
这道题还有一个巨坑,会卡掉一部分人的Dijkstra的代码,比如我,TLE。
为什么呢?
很多人写代码像这样
while(!pq.empty()){ pair<ll,int> p = pq.top();pq.pop(); int u = p.secon 4000 d; for(int e = head[u];e != -1;e = es[e].nxt){ int v = es[e].v; ll w = es[e].w; if(wa[v] > 2*w+wa[u]){ wa[v] = wa[u]+2*w; pq.push(make_pair(wa[v],v)); } } }
这样写过不了第18组测试数据,因为这样一组极端数据就卡掉了
n = 200000,m = 199999
200000 1 2
200000 2 4
200000 3 6
200000 4 8
…..
假如优先队列运行时访问点的顺序是1、2、3、…、200000
那么优先队列里面会有199999个(dist[200000],200000)点对。
而每有一个这样的点对,都将会把200000的边全都遍历一边。
时间复杂度就会增加到20000022000002显然爆炸,所以要把优先队列里面多余点对删掉。
在u点被取出时,增加一句。
if(wa[u] < p.first) continue;
至此,这道题就AC啦。
代码
#include <cstdio> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <cstring> using namespace std; typedef long long ll; typedef pair<ll,int> pli; const int maxn = 2e5+10; priority_queue<pli,vector<pli>,greater<pli> > pq; ll wa[maxn]; struct edge{ int u,v,nxt;ll w; }es[maxn<<1]; int head[maxn],vis[maxn]; int cnt = 0,n,m; void addedge(int u,int v,ll w){ es[cnt].u = u,es[cnt].v = v,es[cnt].nxt = head[u],es[cnt].w = w; head[u] = cnt++; } void solve(){ while(!pq.empty()){ pair<ll,int> p = pq.top();pq.pop(); int u = p.second; if(wa[u] < p.first) continue; for(int e = head[u];e != -1;e = es[e].nxt){ int v = es[e].v; ll w = es[e].w; if(wa[v] > 2*w+wa[u]){ wa[v] = wa[u]+2*w; pq.push(make_pair(wa[v],v)); } } } } int main(){ memset(head,-1,sizeof(head)); cin>>n>>m; for(int i = 0;i < m;++i){ int u,v; ll w; scanf("%d%d%lld",&u,&v,&w); addedge(u,v,w); addedge(v,u,w); } for(int i = 1;i <= n;++i) { ll w; scanf("%lld",&w); wa[i] = w; pq.push(make_pair(w,i)); } solve(); for(int i = 1;i <= n;++i) printf("%lld ",wa[i]); return 0; }
相关文章推荐
- 这是以前别人发的帖子,我整理了一下,都是一些很有趣的题目。
- CodeForces 20C Dijkstra?
- 有趣的C笔试题目(收集)
- 一道有趣的题目
- CodeForces - 391B Word Folding(题目超难题解超简单的DP)
- 一道有趣的C#考试题目
- 谈谈一些有趣的CSS题目(八)-- 纯CSS的导航栏Tab切换方案
- 一道有趣的题目
- CodeForces 25BPhone numbers(简单的字符串模拟题目)
- 有趣的 CSS 题目(8):纯CSS的导航栏Tab切换方案
- Codeforces 232A Cycles 比较有趣的思路题
- 谈谈一些有趣的CSS题目(十四)-- 纯 CSS 方式实现 CSS 动画的暂停与播放!
- bzoj有趣的题目
- Codeforces 部分题目题解(口胡)
- 今天学习的时候偶然发现了一个有趣的题目,可以用编程实现。
- HDOJ题目2544 最短路(最短路径问题,Dijkstra模板)
- pku 3159 Candies 第一道Dijkstra+堆维护+差分约束系统的题目
- BZOJ-几道比较有趣的题目
- 前几天遇到一道有趣的题目 一座楼有10层,兔子可以跳跃的层数可以为1,2或者3,那么兔子到达10层有多少种跳法并列出各种情况。
- 看了张老师的视频--------两个有趣的面向对象题目