60 pts 求调
查看原帖
60 pts 求调
833737
Lyw_and_Segment_Tree楼主2024/2/24 21:36

用的普通 BFS ,3WA + 1TLE:

#include<bits/stdc++.h>
using namespace std;
bool vis[1005][1005];
int a[1005][1005],dis[1005][1005];
int dx[] = {0,0,-1,1};
int dy[] = {1,-1,0,0};
int n,m;
struct node{
    int x,y;
};
node g[1000005];
void bfs(int x,int y){
    queue<node> q;
    q.push((node){x,y});
    dis[x][y] = 0;
    vis[x][y] = true;
    int nx,ny;
    node now;
    while(!q.empty()) {
        now = q.front();
        q.pop();
        for(int i = 0; i < 4; i++) {
            nx = dx[i] + now.x;
            ny = dy[i] + now.y;
            if(nx >= 1 && nx <= m && ny >= 1 && ny <= n && vis[nx][ny] == false && a[nx][ny] != 1) {
                dis[nx][ny] = dis[now.x][now.y] + 1;
                vis[nx][ny] = true;
                q.push((node){nx,ny});
            }
        }
    }
}
int main(){
    memset(dis,0,sizeof(dis));
    memset(vis,0,sizeof(vis));
    int tx,ty,gx,gy,qx,qy,cnt = 0;
    cin >> n >> m;
    for(int i = 1; i <= m; i++) {
        for(int j = 1; j <= n; j++) {
            cin >> a[i][j];
            if(a[i][j] == 2) tx = i, ty = j;
            if(a[i][j] == 4) {
                g[cnt++] = ((node){i,j});
            }
            if(a[i][j] == 3) qx = i, qy = j;
        }
    }
    int sum[cnt];
    for(int i = 0; i < cnt ;i++){
        gx = g[i].x;
        gy = g[i].y;
    	memset(vis,0,sizeof(vis));
    	memset(dis,0,sizeof(dis));
    	bfs(gx,gy);
        sum[i] = dis[qx][qy] + dis[tx][ty];
    }
    int ans = INT_MAX;
    for(int i = 0; i < cnt; i++) {
    	ans = min(ans, sum[i]);
    }
    cout << ans << endl;
}
2024/2/24 21:36
加载中...