hdu2717 Catch That Cow----BFS

来源:互联网 发布:js syntax error 编辑:程序博客网 时间:2024/05/18 22:15

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

一道简单的BFS啊,怎么当时脑子就弯了呢?当时没想到visited标记数组,导致一直超时!!!

#define _CRT_SECURE_NO_DEPRECATE #include<iostream>#include<array>#include<vector>#include<queue>using namespace std;int n, k;int visited[100005];struct Node{    int pos;    int step;    Node(){}    Node(int _pos,int _step):pos(_pos),step(_step){}};int bfs(){    queue<Node> Q;    Node node(n, 0);    Q.push(node);    visited[n] = 1;    while (!Q.empty())    {        Node temp = Q.front();        Q.pop();        if (temp.pos == k)            return temp.step;        if (temp.pos - 1 >= 0 && visited[temp.pos - 1] == 0)        {            Q.push(Node(temp.pos - 1, temp.step + 1));            visited[temp.pos - 1] = 1;        }        if (temp.pos + 1 <= 100000 && visited[temp.pos + 1] == 0)        {            Q.push(Node(temp.pos + 1, temp.step + 1));            visited[temp.pos + 1] = 1;        }        if (temp.pos * 2 <= 100000 && visited[temp.pos * 2] == 0)        {            Q.push(Node(temp.pos * 2, temp.step + 1));            visited[temp.pos * 2] = 1;        }    }    return -1;}int main(){    while (~scanf("%d%d", &n, &k))    {        memset(visited, 0, sizeof(visited));        cout << bfs() << endl;    }    return 0;}
1 0
原创粉丝点击