CodeForces 689B Mike and Shortcuts(SPFA)
来源:互联网 发布:matlab创建稀疏矩阵 编辑:程序博客网 时间:2024/06/05 00:33
题目链接:http://codeforces.com/problemset/problem/689/B
题意:设从i到j需要 |i-j| 点体力,从i有一条捷径到Ai,只需1点体力。输入A1-An,输出从1到i的最少花费。
思路:1->3若没有捷径则相当于1->2->3,所以对于i点只需要建立三条边。i -> Ai、i -> i-1、i -> i+1,然后用SPFA求最短路即可。
#include <stdio.h>#include <stdlib.h>#include <math.h>#include <string.h>#include <iostream>#include <algorithm>#include <vector>#include <queue>using namespace std;const int N = 200005;struct edge{ int to; int cost; edge() {} edge(int a, int b) { to = a; cost = b; }};int d[N];int vis[N];vector<edge> v[N];void add_edge(int s,int t,int cost){ v[s].push_back(edge(t,cost));}void SPFA(int s){ queue<int> q; q.push(s); memset(d,0x3f,sizeof(d)); memset(vis,0,sizeof(vis)); vis[s]=1; d[s]=0; while(!q.empty()) { int p=q.front(); q.pop(); vis[p]=0; for(int i=0;i<v[p].size();i++) { edge e=v[p][i]; if(d[e.to]>e.cost+d[p]) { d[e.to]=e.cost+d[p]; if(!vis[e.to]) { q.push(e.to); vis[e.to]=1; } } } }}int main(){ int n; while(cin>>n) { for(int i=0;i<N;i++) v[i].clear(); for(int i=1;i<=n;i++) { if(i!=n) { add_edge(i,i+1,1); add_edge(i+1,i,1); } int x; scanf("%d",&x); add_edge(i,x,1); } SPFA(1); for(int i=1;i<n;i++) { printf("%d ",d[i]); } printf("%d\n",d[n]); } return 0;}
0 0
- CodeForces 689B Mike and Shortcuts(SPFA)
- CodeForces 689 B. Mike and Shortcuts(SPFA)
- CodeForces 689B - Mike and Shortcuts
- codeforces 689B Mike and Shortcuts (bfs)
- CodeForces 689B BFS-Mike and Shortcuts
- day6 CodeForces 689B Mike and Shortcuts
- CodeForces 689B Mike and Shortcuts
- Codeforces 689B. Mike and Shortcuts(BFS)
- 【打CF,学算法——三星级】CodeForces 689B Mike and Shortcuts (最短路+spfa)
- Codeforces 689B Mike and Shortcuts DFS or BFS
- Codeforces #361 (Div. 2)B-Mike and Shortcuts(spfa最短路)
- Mike and Shortcuts CodeForces
- 文章标题 Coderforces 689B : Mike and Shortcuts (BFS)
- B. Mike and Shortcuts(cf#361)
- Codeforces Round #361 (Div. 2) B. Mike and Shortcuts
- Codeforces Round #361 (Div. 2) B - Mike and Shortcuts
- Codeforces Round #361 (Div. 2) B. Mike and Shortcuts
- Codeforces Round #361 (Div. 2)B. Mike and Shortcuts
- HTTP首部学习笔记
- Android 播放音乐
- JMS之activemq消息持久化
- $(document).ready() 和 window.onload 的区别
- mybatis之annotation(一)
- CodeForces 689B Mike and Shortcuts(SPFA)
- bash shell:脚本中修改profile文件更新LD_LIBRARY_PATH的示例
- struts2使用注解--ACTION中的应用
- 计算的本质:有关表示,编译,赋值,异步和流的杂谈
- HDOJ 3790 Balanced Number
- 深入理解Java中为什么内部类可以访问外部类的成员
- EL表达式从request和session中取值
- Android获取屏幕宽度和动态调整空间宽高
- URI和URL的区别和联系