【备战蓝桥杯国赛-国赛真题】迷宫

题目地址:链接

题目描述

在这里插入图片描述

思路

问题转化成图论,等价于一个连通图中的每条边的权值都是1,要求每个点到一个特定点的最短距离总和,由于每条权值都为1,这样的最短路我们可以用BFS来求,但是要求所有点到一个确定点的最短距离,如果对每一个点都进行一次BFS,那么时间复杂度会是2000 ^ 3,超时,我们反过来思考,这等价于以确定点开始,求其到其他所有点的最短路,这就很好写了,我们以确定点为起点开始BFS即可。

代码(C++)

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>

#define x first
#define y second

using namespace std;

typedef pair<int, int> PII;

const int N = 2010;

int n, m;
int dist[N][N];
vector<PII> e[N][N];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

void bfs() {
    queue<PII> q;
    q.push({n, n});

    memset(dist, 0x3f, sizeof dist);
    dist[n][n] = 0;
    while(q.size()) {
        auto u = q.front(); q.pop();

        int x = u.x, y = u.y;
        for(int i = 0; i < 4; i ++) {
            int a = x + dx[i], b = y + dy[i];
            if(a >= 1 && a <= n && b >= 1 && b <= n) {
                if(dist[a][b] > dist[x][y] + 1) {
                    dist[a][b] = dist[x][y] + 1;
                    q.push({a, b});
                }
            }
        }

        for(auto ne : e[x][y]) {
            int a = ne.x, b = ne.y;
            if(dist[a][b] > dist[x][y] + 1) {
                dist[a][b] = dist[x][y] + 1;
                q.push({a, b});
            }
        }
    }
}

int main() {
    cin >> n >> m;
    for(int i = 0; i < m; i ++) {
        int x1, y1, x2, y2;
        cin >> x1 >> y1 >> x2 >> y2;
        e[x1][y1].push_back({x2, y2});
        e[x2][y2].push_back({x1, y1});
    }

    bfs();

    double res = 0;
    for(int i = 1; i <= n; i ++)
        for(int j = 1; j <= n; j ++)
            res += dist[i][j];
    
    printf("%.2lf\n", res / (n * n));
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值