| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 7226 | Accepted: 2429 |
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
==========================
只能在S或A处分裂,满足最小生成树,对每个点都bfs,求出各个点之间的距离,再求最小生成树
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int INF=0x3f3f3f3f;
int dir[4][2]={{-1,0},{0,-1},{0,1},{1,0}};
int dis[111][111],vis[111][111],mark[111][111];
int m,n,cnt;
char map[111][111];
struct point
{
int x,y,step,id;
}a[333],p,temp;
bool check(int x,int y)
{
if(x>=1&&x<=n&&y>=1&&y<=m) return 1;
else return 0;
}
void bfs(point start)
{
int num=0;
queue<point>que;
p.x=start.x;p.y=start.y;p.step=0;
que.push(p);
vis[p.x][p.y]=1;
while(!que.empty())
{
temp=que.front();
que.pop();
for(int i=0;i<4;i++)
{
p.x=temp.x+dir[i][0];
p.y=temp.y+dir[i][1];
p.step=temp.step+1;
if(!check(p.x,p.y)||map[p.x][p.y]=='#'||vis[p.x][p.y]) continue;
que.push(p);
vis[p.x][p.y]=1;
if((map[p.x][p.y]=='A'||map[p.x][p.y]=='S'))
{
if(dis[ mark[p.x][p.y] ][start.id]==INF)
dis[ mark[p.x][p.y ]][start.id]=dis[start.id][ mark[p.x][p.y] ]=p.step;
num++;
}
if(num==cnt-1) return;
}
}
}
int prim(int s)
{
int res=0,vis[111],d[111];
for(int i=1; i<=cnt; i++)
{
d[i]=INF;
vis[i]=false;
}
d[s]=0;
while(1)
{
int u=0,mn=INF;
for (int i=1;i<=cnt;i++)
{
if (!vis[i]&&d[i]<mn)
{
mn=d[i];
u=i;
}
}
if(u==0) break;
vis[u]=true;
res+=mn;
//cout<<"u="<<u<<" res="<<res<<" "<<endl;
for (int i=1;i<=cnt;i++)
{
if (d[i]>dis[u][i]&&u!=i)
d[i]=dis[u][i];
}
}
return res;
}
int main()
{
int T;char str[1111];
scanf("%d",&T);
while(T--)
{
memset(dis,INF,sizeof(dis));
memset(mark,0,sizeof(mark));
scanf("%d%d",&m,&n);
gets(str);
cnt=0;
for(int i=1;i<=n;i++)
{
gets(map[i]+1);
for(int j=1;j<=m;j++)
{
if(map[i][j]=='S'||map[i][j]=='A')
{
a[++cnt].id=cnt;
a[cnt].x=i;
a[cnt].y=j;
mark[i][j]=cnt;
}
}
}
for(int i=1;i<=cnt;i++)
dis[i][i]=0;
for(int i=1;i<=cnt;i++)
{
memset(vis,0,sizeof(vis));
bfs(a[i]);
}
/*for(int i=1;i<=cnt;i++)
{
for(int j=1;j<=cnt;j++)
cout<<dis[i][j]<<" ";
cout<<endl;
}*/
printf("%d\n",prim(1));
}
return 0;
}
2558



被折叠的 条评论
为什么被折叠?



