• UVA 11573 Ocean Currents --BFS+优先队列


    采用优先队列做BFS搜索,d[][]数组记录当前点到源点的距离,每次出队时选此时eng最小的出队,能保证最先到达的是eng最小的。而且后来用普通队列试了一下,超时。。所以,能用优先队列的,就要用优先队列。

    代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    #include <queue>
    using namespace std;
    #define N 1003
    
    struct node
    {
        int x,y;
        int eng;
        bool operator <(const node &a)const
        {
            return eng>a.eng;
        }
    };
    
    char ss[N][N];
    int dis[N][N];
    int n,m,res;
    int dx[8] = {-1,-1,0,1,1,1,0,-1};
    int dy[8] = {0,1,1,1,0,-1,-1,-1};
    
    bool OK(int nx,int ny)
    {
        if(nx >= 1 && nx <= n && ny >= 1 && ny <= m)
            return true;
        return false;
    }
    
    int bfs(node s,node t)
    {
        priority_queue<node> que;
        while(!que.empty())
            que.pop();
        que.push(s);
        dis[s.x][s.y] = 0;
        while(!que.empty())
        {
            node tmp = que.top();
            que.pop();
            if(tmp.x == t.x && tmp.y == t.y)
                return tmp.eng;
            for(int i=0;i<8;i++)
            {
                node now;
                now.x = tmp.x + dx[i];
                now.y = tmp.y + dy[i];
                if(!OK(now.x,now.y))
                    continue;
                if(ss[tmp.x][tmp.y] - '0' != i)
                    now.eng = tmp.eng + 1;
                else
                    now.eng = tmp.eng;
                if(dis[now.x][now.y] != -1 && now.eng >= dis[now.x][now.y])
                    continue;
                dis[now.x][now.y] = now.eng;
                que.push(now);
            }
        }
        return -1;
    }
    
    int main()
    {
        int i,j,q;
        node s,t;
        while(scanf("%d%d",&n,&m)!=EOF)
        {
            for(i=1;i<=n;i++)
                scanf("%s",ss[i]+1);
            scanf("%d",&q);
            while(q--)
            {
                memset(dis,-1,sizeof(dis));
                scanf("%d%d%d%d",&s.x,&s.y,&t.x,&t.y);
                s.eng = 0;
                res = bfs(s,t);
                printf("%d
    ",res);
            }
        }
        return 0;
    }
    View Code
  • 相关阅读:
    运算优先级
    (5).plus(3).minus(2);
    画图
    函数的三种角色
    表格排序
    正则表达式
    call apply
    css文本属性和边框属性
    css颜色/字体/背景属性
    css选择器优先级及继承
  • 原文地址:https://www.cnblogs.com/whatbeg/p/3582461.html
Copyright © 2020-2023  润新知