Description
Your task is to help the Borg (yes, really) by developing a program which helps the Borg to estimate the minimal cost of scanning a maze for the assimilation of aliens hiding in the maze, by moving in north, west, east, and south steps. The tricky thing is that the beginning of the search is conducted by a large group of over 100 individuals. Whenever an alien is assimilated, or at the beginning of the search, the group may split in two or more groups (but their consciousness is still collective.). The cost of searching a maze is definied as the total distance covered by all the groups involved in the search together. That is, if the original group walks five steps, then splits into two groups each walking three steps, the total distance is 11=5+3+3.
Input
Output
Sample Input
2
6 5 原题肯定没告诉你此处可能会有一串空格
#####
#A#A##
# # A#
#S ##
#####
7 7
#####
#AAA###
# A#
# S ###
# #
#AAA###
#####
Sample Output
8
11
这个题的目的就是,找一个最小生成树,把所有的字母链接起来;
大概思路;
1.输入编号
2.找出每两个字母之间的 权重并储存
3.对于数组中的数据按权重排序
4.并查集+Kruskal算法最小生成树。
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
int v[],mapp[][],vis[][];
int m,n,num,c[]= {,,,-},r[]= {,-,,};
struct node
{
int a;
int b;
int weight;
} s[],p,q;
queue<node>que;
int cmp(const void*a,const void *b)
{
return (*(node*)a).weight-(*(node*)b).weight;
}
int findl(int n)
{
return v[n]==n?n:findl(v[n]);
}
void get()//输入函数
{
int i,j,k=;
char ch;
memset(mapp,,sizeof(mapp));//清零
scanf("%d %d",&n,&m);
char str[];//据说输入m,n后会有很多空格,我就是因为这个WA了一次
gets(str);
m++,n++;
for(i=; i<m; i++)
{
for(j=; j<n; j++)
{
scanf("%c",&ch);
if(ch=='A'||ch=='S')//大于O的表示字母
mapp[i][j]=k++;
if(ch==' ')//-1表示可以走的路
mapp[i][j]=-;
}
getchar();//去掉换行
}
}
void bfs(int i,int j,int step)
{
int a,b,k;
a=p.a=i,b=p.b=j,p.weight=step;
memset(vis,,sizeof(vis));
vis[a][b]=;
que.push(p);
while(!que.empty())
{
p=que.front();
que.pop();
for(k=; k<; k++)
{
if(!mapp[p.a+c[k]][p.b+r[k]]||vis[p.a+c[k]][p.b+r[k]])
continue;
if(mapp[p.a+c[k]][p.b+r[k]]>)//找到字母,将字母序号,权重存入数组
{
s[num].a=mapp[a][b];
s[num].b=mapp[p.a+c[k]][p.b+r[k]];
s[num].weight=p.weight+;
num++;
}
q.a=p.a+c[k],q.b=p.b+r[k],q.weight=p.weight+;
que.push(q);
vis[q.a][q.b]=;
}
} }
int main()
{
int t,i,j,sum; scanf("%d",&t);
while(t--)
{
num=sum=;
get();//输入函数
for(i=; i<m; i++)
{
for(j=; j<n; j++)
{
if(mapp[i][j]>)
bfs(i,j,);
}
}
qsort(s,num,sizeof(node),cmp);//按权值从小到大排序
for(i=; i<; i++)
v[i]=i;
for(i=; i<num; i++)
{
if(findl(s[i].a)!=findl(s[i].b))//简单的并查集
{
sum+=s[i].weight;
v[findl(s[i].a)]=s[i].b;
}
}
printf("%d\n",sum);
}
return ;
}