题解:UVA10307 Killing Aliens in Borg Maze

· · 题解

题意

Borg 队伍可以在起点或者同化完一个外星人之后分裂成多支队伍,总代价为所有队伍走过的步数之和。求同化全部外星人的最小总代价。

解法

  1. 遍历迷宫,收集所有关键点:S 和所有 A,给每个点编号;
  2. 对每一个关键点,跑一次 BFS,求它到其他关键点的距离,建边;
  3. 跑 Kruskal 生成树,输出总权值。

    代码

    #include <bits/stdc++.h>
    #define int long long
    using namespace std;
    const int max_m=1000000,max_n=55;
    int t,n,m;
    int a[max_n][max_n];
    int cnt;
    struct node{
     int u,v,w;
    }e[max_m];
    int f[1005];
    int find(int x){
     if(x==f[x]){
         return x;
     }
     return f[x]=find(f[x]);
    }
    int tot;
    int dist[max_n][max_n],vs[max_n][max_n];
    queue<pair<int,int> >q;
    int dx[]={1,-1,0,0};
    int dy[]={0,0,-1,1};
    void bfs(int x,int y){
     memset(vs,0,sizeof vs);
     memset(dist,0,sizeof dist);
     q.push({x,y});
     dist[x][y]=0;
     while(!q.empty()){
         int sx=q.front().first,sy=q.front().second;
         q.pop();
         if(vs[sx][sy]){
             continue;
         }
         if(a[sx][sy]>0){
             tot++;
             e[tot].w=dist[sx][sy];
             e[tot].u=a[x][y];
             e[tot].v=a[sx][sy];
         }
         vs[sx][sy]=1;
         for(int i=0;i<4;i++){
             int cx=sx+dx[i],cy=sy+dy[i];
             if(cx>n||cx<1||cy>m||cy<1){
                 continue;
             }
             if(a[cx][cy]==-1){
                 continue;
             }
             if(vs[cx][cy]){
                 continue;
             }
             dist[cx][cy]=dist[sx][sy]+1;
             q.push({cx,cy});
         }
     }
    }
    bool cmp(node x,node y){
     return x.w<y.w;
    }
    signed main(){
     cin >> t;
     while(t--){
         cin >> m >> n;
         cnt=0,tot=0;
         char b[1];
         cin.getline(b,1);
         char s[60];
         for(int i=1;i<=n;i++){
             cin.getline(s,50);
             for(int j=1;j<=m;j++){
                 a[i][j]=0;
                 if(s[j-1]=='S'||s[j-1]=='A'){
                     a[i][j]=++cnt;
                 }else if(s[j-1]=='#'){
                     a[i][j]=-1;
                 }
             }
         }
         for(int i=1;i<=cnt;i++){
             f[i]=i;
         }
         for(int i=1;i<=n;i++){
             for(int j=1;j<=m;j++){
                 if(a[i][j]>0){
                     bfs(i,j);
                 }
             }
         }
         int ans=0;
         sort(e+1,e+1+tot,cmp);
         for(int i=1;i<=tot;i++){
             int fu=find(e[i].u),fv=find(e[i].v);
             if(fu!=fv){
                 f[fu]=fv;
                 ans=ans+e[i].w;
             }
         }
         cout << ans << '\n';
     }
     return 0;
    }