UTPC Contest 02-11-22 Div. 2 F. Summit Sunset

如果使用bfs则需要注意每个点都可能被重复更新

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <cstdio>
#include <iomanip>
#include <string>
#include <cstring>
#include <queue>
#include <set>
#include <map>
#include <unordered_map>
#include <sstream>
#include <unordered_set>
const int inf = 0x3f3f3f3f;
const double pi = 4 * atan(1);
#define de(x) cerr<<#x<<"="<<x<<'\n'
#define dde(x,y) cerr<<#x<<'='<<x<<","<<#y<<"="<<y<<'\n'
typedef long long ll;
using namespace std;
typedef pair<int, int>PII;

typedef pair<ll, pair<int, int>>PIII;
//第一个存距离,后面两个存点的坐标x,y
const int N = 510;
ll dist[N][N],maxv, n, g[N][N];
struct nod {
    int x, y;
}ed;
int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
void bfs() {
    dist[0][0] = 0;
    priority_queue<PIII, vector<PIII>, greater<PIII>>heap;
    //按首个元素从小到大排序,每次出队都是最小的
    heap.push({ 0,{0,0} });
    while (heap.size()) {
        PIII t = heap.top(); heap.pop();
        int distance = t.first, tx = t.second.first, ty = t.second.second;
        for (int i = 0; i < 4; i++) {
            int x = tx + dx[i], y = ty + dy[i];
            if (x < 0 || y < 0 || x >= n || y >= n)continue;
            ll d = (g[tx][ty] - g[x][y]) * (g[tx][ty] - g[x][y]);
            //原来的点到新点的距离
            if (dist[x][y] > dist[tx][ty] + d) {
                //这题中每个点不止会更新一次,当点的距离更小的时候把这个点重新入队更新其他点
                dist[x][y] = dist[tx][ty] + d;
                heap.push({ dist[x][y] ,{x,y} });
                
            }
        }
    }
}
int main() {
    ios::sync_with_stdio(false); cin.tie(0);
    cin >> n;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> g[i][j];
            dist[i][j] = inf;//初始化
            if (g[i][j] > maxv) {//找最大的山顶
                maxv = g[i][j];
                ed = { i,j };
            }
        }
    }
    bfs();
    cout << dist[ed.x][ed.y] << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值