• hdu 1242(bfs)


    读完题第一个想法就是以每个friend的位置为起点依次bfs出step,取最小值。提交后WA,修改再提交TLE。

    这题是多对一的搜索,反过来就是一对多,第一个搜到的friend所需的step即为最小值。改完后再提交依旧WA...

    看了下别人的解题报告,基本都是用的优先队列,无奈看了下优先队列的内容,发现也不是想象中那么复杂。在struct

    中加上了自定义优先级operator<稍微一改便AC了。猛然发现优先队列这么好用...

    C++提交 Exe.Time 31   MS Exe.Memory 288k

    G++提交 Exe.Time 187 MS   Exe.Memory 356 KB

    /*若自定义operator为>则会编译不过(G++编译器)

    因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系。

    而且自定义类型的<操作符与>操作符并无直接联系,故会编译不过。 */

    #include<iostream>
    #include<cstdio>
    #include<queue>
    using namespace std ;
    char map[201][201] ;
    int tur[4][2] = {010, -1, -1010} ;
    int n, m ;
    struct node{
        int x, y ;
        int step ;
        friend bool operator <(node t1, node t2){//自定义优先级
            return t1.step > t2.step ;
        }
    }start;
    void bfs(node begin){
        priority_queue<node> q ;//优先队列
        q.push(begin) ;
        while(!q.empty()){
            node p = q.top() ;
            q.pop() ;
            for(int i=0; i<4; i++){
                node temp = p ;
                temp.x += tur[i][0] ;
                temp.y += tur[i][1] ;
                if(temp.x>=0&&temp.x<n&&temp.y>=0&&temp.y<m&&map[temp.x][temp.y]!='#'){
                    temp.step = p.step + 1 ;
                    if(map[temp.x][temp.y]=='r'){
                        printf("%d\n", temp.step) ;
                        return ;
                    }
                    if(map[temp.x][temp.y]=='x'){
                        temp.step ++ ;
                        //map[temp.x][temp.y]=='.' ;
                    }
                    map[temp.x][temp.y] = '#' ;
                    q.push(temp) ;
                }
            }
        }
        printf("Poor ANGEL has to stay in the prison all his life.\n") ;
        return ;
    }
    int main(){
        while(~scanf("%d%d", &n, &m)){
            for(int i=0; i<n; i++)
                for(int j=0; j<m; j++){
                    cin >> map[i][j] ;
                    if(map[i][j]=='a'){
                        start.x = i ;
                        start.y = j ;
                        start.step = 0 ;
                    }
                }
            bfs(start) ;
        }
        return 0 ;
    }

  • 相关阅读:
    CSS中关于BFC的背后原理是什么
    CSS中浏览器是怎样解析CSS选择器的?
    JavaScript中关于 == 和 === 的区别是什么?
    JavaScript中关于继承的实现方式
    Vue双向绑定原理
    Node之TinyPNG图片无限次数压缩
    React的生命周期示意图
    Image-webp探究
    JavaScript中关于事件的循环机制
    vue导航点击切换 1.0
  • 原文地址:https://www.cnblogs.com/xiaolongchase/p/2269431.html
Copyright © 2020-2023  润新知