跳到正文

个人记录

现状

nsp约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月27日
更新
2025年12月27日
篇幅
约 5 分钟

版本

  1. v1当前

代码如下:

C++
#include<bits/stdc++.h>
using namespace std;
// #pragma GCC opztime(2) // 开启O2优化
const int N = 60,M = 1e6; // 最大数据范围
struct node{
    int x,y,step = 0;
};
vector<node> stations;
struct Cmp{
    inline bool operator()(node n1,node n2)const{
        return n1.step > n2.step;
    }
};
priority_queue<node,vector<node>,Cmp> que;//队列
int n,m,d,x_s,y_s,x_t,y_t;
int t1,t2,t3;
char ch;
char mp[N][N];
int x,y,step,dx[] = {1,-1,0,0},dy[] = {0,0,1,-1};
inline void find_airport(const int &pos_x,const int &pos_y,const int& stp){
    queue<node> _que;
    int x,y,step;
    bool used[N][N];
    memset(used,0,sizeof used);
    _que.push({pos_x,pos_y,0});
    while(_que.size()){//寻找合适的机场
        x = _que.front().x;
        y = _que.front().y;
        step = _que.front().step;
        _que.pop();
        if(used[x][y])continue;
        if(step > d)return;
        used[x][y] = 1;
        if(x <= 0 || x > n || y <= 0 || y > m)continue;//判断越界
        if(mp[x][y] == 'A'){
            que.push({x,y,stp+step*t3});
        }
        for(int i = 0;i<4;++i){
            if(!used[x+dx[i]][y+dy[i]])_que.push({x+dx[i],y+dy[i],step+1});
        }

    }
}
inline int bfs(){
    que.push({x_s,y_s,0});
    while(que.size()){
        x = que.top().x;
        y = que.top().y;
        step = que.top().step;
        que.pop();
        if(mp[x][y] == '$')continue;//防止重复访问or山川
        if(x <= 0 || x > n || y<=0 || y > m)continue;//防止越界
        if(x == x_t && y == y_t)return step;
        if(mp[x][y] == 'A'){//广搜寻找所有合适的机场
            find_airport(x,y,step);
        }else if(mp[x][y] == 'T'){
            for(int i = 0;i<stations.size();++i){
                node &obj = stations[i];//引用访问
                if(mp[obj.x][obj.y] == '$'){//消除无效元素
                    swap(obj,*stations.rbegin());//换到最后面
                    stations.pop_back();
                }else{
                    que.push({obj.x,obj.y,step+(abs(x - obj.x)+abs(y - obj.y))*t2});
                }
            }
        }
        for(int i = 0;i<4;++i){//公路
            que.push({x+dx[i],y+dy[i],step+t1});
        }
        mp[x][y] = '$';//染色
    }
    return -1;
}
int main(int argc,char* argv[]){
    scanf("%d%d%d",&n,&m,&d);
    scanf("%d%d%d%d",&x_s,&y_s,&x_t,&y_t);
    scanf("%d%d%d",&t1,&t2,&t3);
    getchar();//读换行符
    for(int i = 1;i<=n;++i){
        for(int j = 1;j<=m;++j){
            ch = getchar();
            mp[i][j] = ch;
            if(ch == 'T')stations.push_back({i,j,0});
            // else if(ch == 'A')airports.push_back({i,j,0});
        }
        getchar();//读换行符
    }
    printf("%d\n",bfs());
    return 0;
}

原题

我认为还能再优化

原文