[BFS] POJ 3278

一维的广搜,写过二维三维之后写起来就很爽了,简洁不少hhhh

看到有2×的跳步还怕有什么陷阱,不过照着板子打就过了hhh

还是要判断边界值,要不Runtime Error


对了,第一次亲自遇到了memset的错误

总之这几个是可以用的

memset 0

memset int类 -1

memset int类 0x3f 大约10亿6千万

memset int类 0x7f max_int


#include 
#include 
#include 
#include 

using namespace std;

struct Node {
        int x;
        int time;

        bool operator< ( const Node t ) const { return time > t.time; }
} cur, nex;

const int maxn = 100001;
int mintime[ maxn ];

//三种方向
int dir ( int x, int i ) {
        if ( i == 0 )
                return 2 * x;
        else if ( i == 1 )
                return x - 1;
        else
                return x + 1;
}

bool path ( int x ) { return x < maxn ? true : false; }

int bfs ( int c, int cow ) {
        priority_queue q;

        cur.x = c;
        cur.time = 0;
        mintime[ c ] = 0;
        q.push ( cur );

        while ( !q.empty () ) {
                cur = q.top ();
                q.pop ();

                if ( cur.x == cow )
                        return cur.time;

                for ( int i = 0; i <= 2; i++ ) {
                        nex.x = dir ( cur.x, i );
                        nex.time = cur.time + 1;

                        if ( path ( nex.x ) && nex.time < mintime[ nex.x ] ) {
                                mintime[ nex.x ] = nex.time;
                                q.push ( nex );
                        }
                }
        }
        return -1;
}

int main () {
        int n, k;
        while ( ~scanf ( "%d%d", &n, &k ) ) {

                memset ( mintime, 0x7f, sizeof ( mintime ) );
                int m;
                //只能回退
                if ( n >= k )
                        m = n - k;
                else
                        m = bfs ( n, k );
                printf ( "%d\n", m );
        }

        return 0;
}


你可能感兴趣的:(ACM,kuangbin专题一,简单搜索)