跳到正文

题解

题解:UVA10307 Killing Aliens in Borg Maze

chenjunyu2014约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年10月29日
收录
2026年11月16日
更新
2026年11月16日
篇幅
约 4 分钟
获赞
1
题目
UVA10307

版本

  1. v1当前

题意理解

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

整体思路

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

坑点(非常重要!!!)

输入读入陷阱:第一行两个数是行、列,后面一整行迷宫包含空格,C++ 里用 cin 会跳过换行,容易读错;推荐用 getline,注意吸收换行符

时间复杂度

nn 表示矩阵长,mm 表示矩阵宽,kk 表示外星人个数。

搜索复杂度:O(nmk)O(nmk)。

最小生成树复杂度:O(k2log⁡k2+k2)O(k^2\log{k^2}+k^2)。

代码

C++
#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;
}
原文