http://acm.hdu.edu.cn/showproblem.php?pid=1242

读完题第一个想法就是以每个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 ;
}

posted on 2011-11-30 17:40  追逐.  阅读(302)  评论(0编辑  收藏  举报