Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 6634 | Accepted: 2240 |
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
Source
//============================================================================
// Name : POJ.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================ #include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <map>
using namespace std; char g[][];
int n,m;
int a[][];
int move[][]={{,},{-,},{,},{,-}}; int cost[][];
int t[][];
void bfs(int sx,int sy)
{
queue<pair<int,int> >q;
while(!q.empty())q.pop();
memset(t,-,sizeof(t));
t[sx][sy]=;
q.push(make_pair(sx,sy));
while(!q.empty())
{
pair<int,int> now=q.front();
q.pop();
if(a[now.first][now.second]!=-)
cost[a[sx][sy]][a[now.first][now.second]]=t[now.first][now.second];
for(int i=;i<;i++)
{
int tx=now.first+move[i][];
int ty=now.second+move[i][];
if(g[tx][ty]=='#'||t[tx][ty]!=-)continue;
t[tx][ty]=t[now.first][now.second]+;
q.push(make_pair(tx,ty));
}
}
}
const int INF=0x3f3f3f3f;
bool vis[];
int lowc[];
int Prim(int n)
{
int ans=;
memset(vis,false,sizeof(vis));
vis[]=true;
for(int i=;i<n;i++)lowc[i]=cost[][i];
for(int i=;i<n;i++)
{
int minc=INF;
int p=-;
for(int j=;j<n;j++)
if(!vis[j]&&minc>lowc[j])
{
minc=lowc[j];
p=j;
}
if(minc==INF)return -;
ans+=minc;
vis[p]=true;
for(int j=;j<n;j++)
if(!vis[j]&&lowc[j]>cost[p][j])
lowc[j]=cost[p][j];
}
return ans;
} int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&m,&n);
gets(g[]);
memset(a,-,sizeof(a));
int tol=;
for(int i=;i<n;i++)
{
gets(g[i]);
for(int j=;j<m;j++)
if(g[i][j]=='A'||g[i][j]=='S')
a[i][j]=tol++;
}
for(int i=;i<n;i++)
for(int j=;j<n;j++)
if(a[i][j]!=-)
bfs(i,j);
printf("%d\n",Prim(tol));
}
return ;
}