openjudge2971 抓住那头牛

奇葩做法,跑最短路,我用的SPFA

#include 
#include 
#include 
#include 
#include 
using namespace std;
const int MAXN = 400000+5;
int n,k,head[MAXN],tot,nxt[MAXN<<1],dis[MAXN << 1];
bool vis[MAXN];
struct Edge
{
    int from,to,cost;
}e[MAXN<<1];
queue<int >q;
void build(int f,int t,int d)
{
    e[++tot].from = f;
    e[tot].to = t;
    e[tot].cost = d;
    nxt[tot] = head[f];
    head[f] = tot;
}
void spfa(int s)
{
    memset(dis,0x3f,sizeof(dis));
    vis[s] = 1;
    dis[s] = 0;
    q.push(s);
    while(!q.empty())
    {
        int x = q.front();
        q.pop();
        vis[x] = 0;
        for(int i = head[x] ; i ; i = nxt[i])
        {
            int v = e[i].to;
            if(dis[v] > dis[x]+e[i].cost)
            {
                dis[v] = dis[x] + e[i].cost;
                if(!vis[v])
                {
                    vis[v] = 1;
                    q.push(v);
                }
            }
        }
    }
}
int main()
{
    scanf("%d%d",&n,&k);
    for(int i = 1; i <= 100001 ; i ++)
    {
        build(i,i+1,1);
        build(i+1,i,1);
        build(i,i-1,1);
        build(i-1,i,1);
        build(i,i*2,1);
    }
    if(n < k)
    {
        spfa(n);
        printf("%d\n",dis[k]);
    }
    else if(n == k)
    {
        puts("0");
    }
    else if(n > k)
    {
        printf("%d\n",n-k );
    }
    return 0;
}

你可能感兴趣的:(图论,spfa,最短路,openjudge)