题目链接:http://codeforces.com/problemset/problem/689/B
--------------------------------------------------------------------------------
题意:在一条直线上有n个城市,相邻两个城市之间的花费为1,但是有捷径,可以到捷径所在的点,而且只需要1的花费,捷径不能前往之前的城市。
思路:经典的,bfs打板直接过。唯一要注意的是这种情况,如4-7有捷径,所以有可能到6的最短路径为4-7-6。注意判断捷径之后往回走的可能性。第一次没注意,WA了一发~~~
代码:
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> #include<vector> #include<stack> #include<bitset> #include<cstdlib> #include<cmath> #include<set> #include<list> #include<deque> #include<map> #include<queue> using namespace std; typedef long long ll; const double PI = acos(-1.0); const double eps = 1e-6; const int MAXN =2e5+10; const int INF = 1e9; int a[MAXN]; int dis[MAXN]; int n =0; void bfs(){ queue<int> q; q.push(1); while(!q.empty()){ int cur =q.front(); q.pop(); if(cur<n&&dis[cur+1]>dis[cur]+1){ dis[cur+1]=dis[cur]+1; q.push(cur+1); }if(dis[a[cur]]>dis[cur]+1&&a[cur]>cur){ dis[a[cur]]=dis[cur]+1; q.push(a[cur]); }if(cur>1&&cur<=n&&dis[cur-1]>dis[cur]+1){ dis[cur-1]=dis[cur]+1; q.push(cur-1); } } } int main(void){ scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); dis[i] = INF; } dis[1]=0; bfs(); for(int i=1;i<=n;i++){ printf("%d ",dis[i]); } printf("\n"); return 0; }