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
原创粉丝点击