链接:
http://poj.org/problem?id=3026
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=82831#problem/J
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10713 | Accepted: 3559 |
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
代码:
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std; const int maxn = ;
const int oo = 0xfffffff; int dir[][] = { {,},{,},{-,},{,-} };
char G[maxn][maxn]; //保存地图
int D[maxn][maxn]; //记录两点间的距离
int use[maxn][maxn]; //标记地图
int Index[maxn][maxn]; //记录‘A’或者‘B’的编号
struct node{int x, y, step;}; void BFS(int k, int M,int N, int x, int y)
{
queue<node> Q;
node s;
s.x = x, s.y = y, s.step = ;
use[s.x][s.y] = k; Q.push(s); while(Q.size())
{
s = Q.front();Q.pop();
if(G[s.x][s.y]>='A' && G[s.x][s.y] <='Z')
D[k][ Index[s.x][s.y] ] = s.step; for(int i=; i<; i++)
{
node q = s;
q.x += dir[i][], q.y += dir[i][]; if(q.x>=&&q.x<M && q.y>=&&q.y<N && G[q.x][q.y]!='#' && use[q.x][q.y]!=k)
{
use[q.x][q.y] = k;
q.step += ;
Q.push(q);
}
}
}
}
int Prim(int N) //这里面的N代表编号最多到N
{
int i, dist[maxn], vis[maxn]={, };
int ans = , T=N-; for(i=; i<=N; i++)
dist[i] = D[][i]; while(T--)
{
int k=, mini = oo; for(i=; i<=N; i++)
{
if(!vis[i] && mini > dist[i])
mini = dist[i], k=i;
}
ans += mini;
vis[k] = true; for(i=; i<=N; i++)
if(!vis[i])dist[i] = min(dist[i], D[k][i]);
} return ans;
} int main()
{
int T; scanf("%d", &T); while(T--)
{
int i, j, M, N, t=; scanf("%d%d ", &N, &M); for(i=; i<M; i++)
{
gets(G[i]);
for(j=; j<N; j++)
{
if(G[i][j]>='A' && G[i][j]<='Z')
Index[i][j] = t++;
use[i][j] = ;
}
} for(i=; i<M; i++)
for(j=; j<=N; j++)
{
if(G[i][j]>='A' && G[i][j]<='Z')
BFS(Index[i][j], M, N, i, j);
} int ans = Prim(t-); printf("%d\n", ans);
} return ;
}