Link: Http://codeforces.com/contest/689/problem/B
question: The problem is very long, but in fact there are N cities, the city I to the city J need to spend is |i-j|, and each city has a shortcut directly from I spend 1 to a[i]. Ask for the minimum cost of starting from 1 to each city.
analysis: Know the idea is actually a 3-side map of each point, directly starting from 1 o'clock BFS just.
Code:
#include <map> #include <set> #include <cmath> #include <queue> #include <bitset> #include <math.h> #include <cstdio> #include <vector> #include <string> #include <cstring> # include<iostream> #include <algorithm> #pragma comment (linker, "/stack:102400000,102400000") using
namespace Std;
const int n=200010;
const int max=1000000100;
const int mod=100000000;
const int mod1=1000000007;
const int mod2=1000000009;
const double eps=0.00000001;
typedef long Long LL;
const LL mod=1000000007;
const int inf=1000000010;
Const double Pi=acos (-1.0);
typedef double DB;
typedef unsigned long long ull;
int a[n],d[n],q[n],dis[n];
int main () {int i,n,l=1,r=0;
scanf ("%d", &n);
memset (q,0,sizeof (q));
memset (dis,0x6f,sizeof (dis));
for (i=1;i<=n;i++) scanf ("%d", &a[i]);
D[++r]=1;dis[1]=0;q[1]=1; for (; l<=r;l++) {if (d[l]>1&&!q[d[l]-1]) {q[d[l]-1]=1;dis[d[l]-1]=dis[d[l]]+1;D[++r]=d[l]-1;
} if (D[l]<n&&!q[d[l]+1]) {q[d[l]+1]=1;dis[d[l]+1]=dis[d[l]]+1;d[++r]=d[l]+1;
} if (!q[a[d[l]]]] ({q[a[d[l]]]=1;dis[a[d[l]]]=dis[d[l]]+1;d[++r]=a[d[l]);
} for (i=1;i<=n;i++) printf ("%d", dis[i]);
printf ("\ n");
return 0; }