• poj3278


    BFS,注意判断数组是否越界,注意处理n==k的情况

    View Code
    #include <iostream>
    #include
    <cstdlib>
    #include
    <cstring>
    #include
    <cstdio>
    #include
    <queue>
    using namespace std;

    #define maxn 100005

    struct Item
    {
    int step, pos;
    Item()
    {
    }
    Item(
    int s, int p) :
    step(s), pos(p)
    {
    }
    };

    int visited[maxn];

    int main()
    {
    int n, k;
    //freopen("D:\\t.txt", "r", stdin);
    scanf("%d%d", &n, &k);
    if (n == k)
    {
    printf(
    "0\n");
    return 0;
    }
    memset(visited,
    0, sizeof(visited));
    queue
    <Item> q;
    q.push(Item(
    0, n));
    while (1)
    {
    Item temp;
    temp
    = q.front();
    q.pop();
    if (temp.pos * 2 < maxn && !visited[temp.pos * 2])
    {
    q.push(Item(temp.step
    + 1, temp.pos * 2));
    visited[temp.pos
    * 2] = true;
    }
    if (temp.pos + 1 < maxn && !visited[temp.pos + 1])
    {
    q.push(Item(temp.step
    + 1, temp.pos + 1));
    visited[temp.pos
    + 1] = true;
    }
    if (temp.pos - 1 >= 0 && !visited[temp.pos - 1])
    {
    q.push(Item(temp.step
    + 1, temp.pos - 1));
    visited[temp.pos
    - 1] = true;
    }
    if (visited[k])
    {
    printf(
    "%d\n", temp.step + 1);
    return 0;
    }
    }
    return 0;
    }
  • 相关阅读:
    2020寒假简记
    感知神经网络模型与学习算法
    信息检索模型与评估
    Diffie-Hellman密钥交换
    RSA密码体制
    MySQL基准测试(benchmark)
    MySQL数据引擎
    MySQL 多版本并发控制(MVCC)
    MySQL事务管理
    利用dotnet restore 导入本地 .nupkg 包
  • 原文地址:https://www.cnblogs.com/rainydays/p/1965364.html
Copyright © 2020-2023  润新知