poj 3278 -- Catch That Cow (最短路)

来源:互联网 发布:敬请悉知 编辑:程序博客网 时间:2024/05/17 07:09

建图,以n为源点,n-1,n+1,2*n分别与n建立权值为1的边,题目即转化为了求n到k的最短路

注意搜索加限定条件,容易re

#include<queue>#include<iostream>using namespace std;int a[100001]={0};int bfs(int n,int k){    a[n]=0;    queue<int> q;    q.push(n);    int t=-1;    while(t!=k)    {        t=q.front();        if(t-1>=0&&a[t-1]==0)        a[t-1]=a[t]+1,q.push(t-1);        if(t+1<=100000&&a[t+1]==0)        a[t+1]=a[t]+1,q.push(t+1);        if(2*t<=100000&&a[2*t]==0)        a[t*2]=a[t]+1,q.push(t*2);        q.pop();    }    return a[k];}int main(){    int n,k;    cin>>n>>k;    cout<<bfs(n,k);}


原创粉丝点击