[BFS] HDU 2612

来源:互联网 发布:尚学堂大数据极限班 编辑:程序博客网 时间:2024/06/10 16:49

开始想找到一个@就让Y和M遍历一次,超时

所以只能各遍历一次,记下来时间,再找最小的

开始MIN不是这么写的。。。不知道为啥过不了hhh

#include <cstring>#include <iostream>#include <queue>#define N 205#define inf 0x3f3f3f3fusing namespace std;struct Node {        int x, y;        int cnt;} cur, nex;int n, m;int yx, yy, mx, my;char map[ N ][ N ];int vis[ N ][ N ];//存y,m遍历的时间int ty[ N ][ N ];int tm[ N ][ N ];int dirx[ 4 ] = {1, -1, 0, 0};int diry[ 4 ] = {0, 0, 1, -1};bool path ( int x, int y ) {        if ( x >= 0 && x < n && y >= 0 && y < m && map[ x ][ y ] != '#' )                return true;        return false;}//传入要存时间的数组(是y还是m)void bfs ( int x, int y, int t[][ N ] ) {        memset ( vis, false, sizeof ( vis ) );        cur.x = x, cur.y = y, cur.cnt = 0;        vis[ yx ][ yy ] = true;        vis[ mx ][ my ] = true;        queue<Node> q;        q.push ( cur );        while ( !q.empty () ) {                cur = q.front ();                q.pop ();                //每次找到都记录时间                if ( map[ cur.x ][ cur.y ] == '@' ) {                        t[ cur.x ][ cur.y ] = cur.cnt;                }                for ( int i = 0; i < 4; ++i ) {                        nex.x = cur.x + dirx[ i ];                        nex.y = cur.y + diry[ i ];                        nex.cnt = cur.cnt + 1;                        if ( path ( nex.x, nex.y ) && !vis[ nex.x ][ nex.y ] ) {                                vis[ nex.x ][ nex.y ] = true;                                q.push ( nex );                        }                }        }}int main () {        while ( cin >> n >> m ) {                for ( int i = 0; i < n; ++i )                        cin >> map[ i ];                for ( int i = 0; i < n; ++i )                        for ( int j = 0; j < m; ++j ) {                                if ( map[ i ][ j ] == 'Y' )                                        yx = i, yy = j;                                if ( map[ i ][ j ] == 'M' )                                        mx = i, my = j;                        }                int MIN = inf;                memset ( ty, 0, sizeof ( ty ) );                memset ( tm, 0, sizeof ( tm ) );                //只要两次遍历,要不然肯定超时                bfs ( yx, yy, ty );                bfs ( mx, my, tm );                for ( int i = 0; i < n; ++i )                        for ( int j = 0; j < m; ++j )                                //能到达,且时间更小                                if ( MIN > ty[ i ][ j ] + tm[ i ][ j ] && ty[ i ][ j ] &&                                     tm[ i ][ j ] ) {                                        MIN = ty[ i ][ j ] + tm[ i ][ j ];                                }                cout << MIN * 11 << endl;        }        return 0;}