PKU 3278 Catch That Cow

bfs,需要注意0和N是可以到达的,除此之外也可以到达,但实际上不可能更优,因为超过这个范围表明需要回退,回退的步数超过2时,完全可以多走几步再翻倍,结果更优。

# include <cstdio>

# include <queue>

# include <cstring>



using namespace std;



# define MAXN 100000 + 5
# define N 100000 + 1
int n, k;

char vis[MAXN];

int d[MAXN];



int bfs(void)

{

    queue <int> Q;



    memset(vis, 0, sizeof(vis))    ;



    vis[n] = 1, d[n] = 0;

    Q.push(n);

    while (!Q.empty())

    {

        int x = Q.front(); Q.pop();

        if (x == k) return d[x];

        if (x-1>=0 && !vis[x-1]) {vis[x-1] = 1;Q.push(x-1);d[x-1] = d[x]+1;}

        if (x+1<N && !vis[x+1]) {vis[x+1] = 1;Q.push(x+1);d[x+1] = d[x]+1;}

        if (x*2<N && !vis[x*2]) {vis[x*2] = 1;Q.push(x*2); d[x*2] = d[x]+1;}

    }



    return -1;

}



void solve(void)

{

    printf("%d\n", bfs());

}



int main()

{

    while (~scanf("%d%d", &n, &k))

    {

        solve();

    }



    return 0;

}

你可能感兴趣的:(catch)