Poj 3026 Borg maze [BFS + minimal spanning tree]

Source: Internet
Author: User
Link: http://poj.org/problem? Id = 3026 http://acm.hust.edu.cn/vjudge/contest/view.action? Cid = 22010 # Problem/jborg maze
Time limit:1000 ms   Memory limit:65536 K
Total submissions:6905   Accepted:2315

Description

The Borg is an immensely powerful race of enhanced Humanoids from the Delta Quadrant of the galaxy. the Borg collective is the term used to describe the group consciousness of the Borg civilization. each Borg individual is linked to the collective by a sophisticated
Subspace network that insures each member is given constant supervision and guidance.

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 conducting 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

On the first line of input there is one integer, n <= 50, giving the number of test cases in the input. each test case starts with a line containg two integers x, y such that 1 <= X, Y <= 50. after this, y lines follow, each which x characters. for each character,
A space ''' stands for an open space, a hash mark ''# ''' stands for an obstructing wall, the capital letter ''a' stand for an alien, and the capital letter's ''stands for the start of the search. the perimeter of the maze is always closed, I. E ., there
Is no way to get out from the coordinate of the's '. At most 100 aliens are present in the maze, and everyone is reachable.

Output

For every test case, output one line containing the minimal cost of a succesful search of the Maze leaving no aliens alive.

Sample Input

26 5##### #A#A### # A##S  ####### 7 7#####  #AAA####    A## S ####     ##AAA########  

Sample output

811

Source

Svenskt mästerskap I programmering/norgesmesterskapet 2001

Starting from S, I need to grasp every A and find the smallest total path length. Space is the place where I can go. # No, It is around # Note: it can only be separated in S or a. the space area cannot be split.
Algorithm: min spanning tree + BFS idea: Build a graph and convert it to Min spanning tree, then directly apply the prime or Kruskal Template
Because only the S and a parts can be separated, S and a are the same, use BFs to traverse S and each A to find the shortest distance between them and other points before applying the template.
PS: when we encounter a point [s or a], we will traverse BFs. In fact, if it is a bit BFs, we will find the path again, wasting time, looking at it is not harmonious, but there is no good solution to this question. orz... Pitfall: After the input columns and rows have many spaces, you cannot use getchar () WA three times. After reading the discussion area, you will know that using gets () will pass Kruskal:

3026 Accepted 352 k 63 MS C ++ 2634b 2013-07-31 14:44:02

# Include <stdio. h> # include <string. h >#include <queue >#include <algorithm> using namespace STD; const int maxn = 50 + 10; const int maxp = 100 + 10; int n, m; int map [maxn] [maxn]; // input graph int W [maxp] [maxp]; // path int V [maxn] [maxn]; // mark whether to access int P [maxp]; // Father's Day point int dir [4] [2] = {, 0,-1 }; // Four Directions: struct edge {int U, V; int W;} edge [maxp * maxp]; struct point {int X, Y; int step ;}; void BFS (int x, int y) // traverse the Ma P [x] [Y] points {point; point. X = x; point. y = y; point. step = 0; // The distance from the user to the user is 0 queue <point> q; q. push (point); // start point to join memset (v, 0, sizeof (v); V [x] [Y] = 1; // mark access int num = 1; // number of points found while (! Q. empty () {point now = Q. front (); // gets the first Q. pop (); // departure point next; // find the next point for (INT I = 0; I <4; I ++) // search for the next vertex in four directions: {next. X = now. X + dir [I] [0]; next. y = now. Y + dir [I] [1]; next. step = now. step + 1; // number of steps + 1 // if you can go, and have not been accessed if (Map [next. x] [next. y]> = 0 &&! V [next. x] [next. y]) {q. push (next); // enter the team V [next. x] [next. y] = 1; // mark the accessed if (Map [next. x] [next. y]> 0) // if you are looking for a vertex {// create a graph edge [M]. U = map [x] [Y]; edge [M]. V = map [next. x] [next. y]; edge [M ++]. W = next. step; num ++; If (num = N) return; // all vertices have been found }}}return;} bool CMP (edge a, edge B) {return. W <B. w;} int find (int x) {return x = P [x]? X: P [x] = find (P [x]);} int Kruskal () {int ans = 0; For (INT I = 1; I <= N; I ++) P [I] = I; sort (edge, edge + M, CMP); For (INT I = 0; I <m; I ++) {int u = find (edge [I]. u); int v = find (edge [I]. v); If (u! = V) {P [v] = u; ans + = edge [I]. W ;}} return ans;} int main () {int t; int row, Col; char TMP [maxn]; char C; scanf ("% d ", & T); While (t --) {scanf ("% d", & Col, & Row); gets (TMP ); // pit [a string of spaces] n = m = 0; For (INT I = 1; I <= row; I ++) {for (Int J = 1; j <= Col; j ++) {scanf ("% C", & C); If (C = '#') map [I] [J] =-1; else if (C = '') map [I] [J] = 0; else map [I] [J] = ++ N;} getchar () ;}for (INT I = 0; I <= row; I ++) {for (Int J = 0; j <= Col; j ++) if (Map [I] [J]> 0) BFS (I, j );} int ans = Kruskal (); printf ("% d \ n", ANS);} return 0 ;}
Prime:
3026 Accepted 264 K 63 MS C ++ 2543b 2013-07-31 14:44:34

#include<stdio.h>#include<string.h>#include<queue>#include<algorithm>using namespace std;const int maxn = 50+10;const int maxp = 110;const int INF = maxn*maxn;int n;int map[maxn][maxn];int w[maxp][maxp];int d[maxp];int vis[maxp];int v[maxn][maxn];struct Point{    int x,y;    int step;};int dir[4][2] = {0,1, 1,0, 0,-1, -1,0};void bfs(int x, int y){    Point point;    point.x = x; point.y = y;    point.step = 0;    memset(v,0,sizeof(v));    queue<Point> q;    q.push(point);    v[x][y] = 1;    int num = 1;    while(!q.empty())    {        Point now = q.front();        q.pop();        Point next;        for(int i = 0; i < 4; i++)        {            next.x = now.x+dir[i][0];            next.y = now.y+dir[i][1];            if(map[next.x][next.y] >= 0 && !v[next.x][next.y])            {                next.step = now.step+1;                v[next.x][next.y] = 1;                q.push(next);                if(map[next.x][next.y] > 0)                {                    int u = map[x][y];                    int v = map[next.x][next.y];                    w[u][v] = next.step;                    num++;                    if(num == n) return;                }            }        }    }    return;}int Prime(){    int ans = 0;    for(int i = 1; i <= n; i++) d[i] = INF;    d[1] = 0;    memset(vis, 0, sizeof(vis));    for(int i = 1; i <= n; i++)    {        int x, m = INF;        for(int y = 1; y <= n; y++) if(!vis[y] && d[y] <= m) m = d[x=y];        vis[x] = 1; ans += d[x];        for(int y = 1; y <= n; y++) if(!vis[y])            d[y] = min(d[y], w[x][y]);    }    return ans;}int main(){    int T;    int row, col;    scanf("%d", &T);    while(T--)    {        n = 0;        char c;        scanf("%d%d", &col,&row);        char tmp[51];        gets(tmp);        for(int i = 1; i <= row; i++)        {            for(int j = 1; j <= col; j++)            {                scanf("%c", &c);                if(c == '#') map[i][j] = -1;                else if(c == ' ') map[i][j] = 0;                else map[i][j] = ++n;            }            getchar();        }        for(int i = 1; i <= row; i++)        {            for(int j = 1; j <= col; j++)                if(map[i][j] > 0)                    bfs(i,j);        }        int ans = Prime();        printf("%d \n", ans);    }    return 0;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.