2014廣州網路賽1004||hdu5025 分層最短路

life4711發表於2014-09-22

http://acm.hdu.edu.cn/showproblem.php?pid=5025

Problem Description
《Journey to the West》(also 《Monkey》) is one of the Four Great Classical Novels of Chinese literature. It was written by Wu Cheng'en during the Ming Dynasty. In this novel, Monkey King Sun Wukong, pig Zhu Bajie and Sha Wujing, escorted Tang Monk to India to get sacred Buddhism texts. 

During the journey, Tang Monk was often captured by demons. Most of demons wanted to eat Tang Monk to achieve immortality, but some female demons just wanted to marry him because he was handsome. So, fighting demons and saving Monk Tang is the major job for Sun Wukong to do.

Once, Tang Monk was captured by the demon White Bones. White Bones lived in a palace and she cuffed Tang Monk in a room. Sun Wukong managed to get into the palace. But to rescue Tang Monk, Sun Wukong might need to get some keys and kill some snakes in his way.

The palace can be described as a matrix of characters. Each character stands for a room. In the matrix, 'K' represents the original position of Sun Wukong, 'T' represents the location of Tang Monk and 'S' stands for a room with a snake in it. Please note that there are only one 'K' and one 'T', and at most five snakes in the palace. And, '.' means a clear room as well '#' means a deadly room which Sun Wukong couldn't get in.

There may be some keys of different kinds scattered in the rooms, but there is at most one key in one room. There are at most 9 kinds of keys. A room with a key in it is represented by a digit(from '1' to '9'). For example, '1' means a room with a first kind key, '2' means a room with a second kind key, '3' means a room with a third kind key... etc. To save Tang Monk, Sun Wukong must get ALL kinds of keys(in other words, at least one key for each kind).

For each step, Sun Wukong could move to the adjacent rooms(except deadly rooms) in 4 directions(north, west, south and east), and each step took him one minute. If he entered a room in which a living snake stayed, he must kill the snake. Killing a snake also took one minute. If Sun Wukong entered a room where there is a key of kind N, Sun would get that key if and only if he had already got keys of kind 1,kind 2 ... and kind N-1. In other words, Sun Wukong must get a key of kind N before he could get a key of kind N+1 (N>=1). If Sun Wukong got all keys he needed and entered the room in which Tang Monk was cuffed, the rescue mission is completed. If Sun Wukong didn't get enough keys, he still could pass through Tang Monk's room. Since Sun Wukong was a impatient monkey, he wanted to save Tang Monk as quickly as possible. Please figure out the minimum time Sun Wukong needed to rescue Tang Monk.
 

Input
There are several test cases.

For each case, the first line includes two integers N and M(0 < N <= 100, 0<=M<=9), meaning that the palace is a N×N matrix and Sun Wukong needed M kinds of keys(kind 1, kind 2, ... kind M). 

Then the N × N matrix follows.

The input ends with N = 0 and M = 0.
 

Output
For each test case, print the minimum time (in minutes) Sun Wukong needed to save Tang Monk. If it's impossible for Sun Wukong to complete the mission, print "impossible"(no quotes).
 

Sample Input
3 1 K.S ##1 1#T 3 1 K#T .S# 1#. 3 2 K#T .S. 21. 0 0
 

Sample Output
5 impossible 8
學長的思路:

           利用狀態壓縮列舉有哪幾條蛇在孫悟空行走的過程中被殺死,然後在每一次列舉的時候採用分成最短路的思想,構建虛點(以鑰匙的編碼為分層的依據)。每層內的點相            互建邊,並且那些與下一把鑰匙相鄰的點,和下一把鑰匙所在的點建邊,這類點是跨層的。最後spfa演算法求以孫悟空所在位置為起點的單源最短路就可以了。

值得一提的是:

           在沒蒐集到所有的鑰匙之前,孫是可以經過唐所在的位置和所有鑰匙所在的位置的,這樣就給建邊帶來了方便,不用特殊考慮唐的位置了。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <queue>
#include <string.h>
using namespace std;

const int dir[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
const int INF=0x3f3f3f3f;
const int maxm=511111;
const int maxn=111111;

struct EdgeNode
{
    int to;
    int w;
    int next;
};

EdgeNode edges[maxm];
int N,M;
int head[maxn],edge,n;
bool vis[maxn];
queue <int> que;
int dis[maxn];

void addedge(int u,int v,int c)
{
    edges[edge].w=c,edges[edge].to=v,edges[edge].next=head[u],head[u]=edge++;
}

void init()
{
    memset(head,-1,sizeof(head));
    edge=0;
}

bool spfa(int s)//單源最短路
{
    int u;
    for (int i=0; i<=n; i++)
        dis[i]=INF;
    memset(vis,0,sizeof(vis));
    while (!que.empty()) que.pop();
    que.push(s);
    vis[s]=true;
    dis[s]=0;
    while (!que.empty())
    {
        u=que.front();
        que.pop();
        vis[u]=false;
        for (int i=head[u]; i!=-1; i=edges[i].next)
        {
            int v=edges[i].to;
            int w=edges[i].w;
            if (dis[v]>dis[u]+w)
            {
                dis[v]=dis[u]+w;
                if (!vis[v])
                {
                    vis[v]=true;
                    que.push(v);
                }
            }
        }

    }
    return true;
}

char s[111][111];

int getPos(int dep,int x,int y)
{
    return dep*N*N+x*N+y;
}

int Kill;

struct Point
{
    int x,y;
    Point() {}
    Point(int _x,int _y):x(_x),y(_y) {}//以前沒這麼用過,長知識了
} snake[6];

int snum;
int sx,sy;
int ex,ey;
int ans=INF;

bool check(int x,int y)
{
    if(x>=0&&x<N&&y>=0&&y<N)
        return true;
    return false;
}

int unlock(int dep,int x,int y)
{
    if (s[x][y]>='0'&&s[x][y]<='9')
    {
        int num=s[x][y]-'0';
        if (dep+1==num)
            return 0;
        else
            return 1;
    }
    return -1;
}

int main()
{
    while (~scanf("%d%d",&N,&M))
    {
        if (N==0&&M==0)
            break;
        ans=INF;
        n=(M+1)*N*N;
        snum=0;
        for (int i=0; i<N; i++)
            scanf("%s",s[i]);
        for (int i=0; i<N; i++)
            for (int j=0; j<N; j++)
            {
                if (s[i][j]=='S')
                    snake[snum++]=Point(i,j);
                if (s[i][j]=='K')
                {
                    sx=i;
                    sy=j;
                }
                if (s[i][j]=='T')
                {
                    ex=i;
                    ey=j;
                }
            }
        for (int bit=0; bit<(1<<snum); bit++) //列舉哪些蛇這行走過程中被殺了
        {
            Kill=0;
            for (int k=0; k<snum; k++)
                if (bit&(1<<k))
                {
                    Kill++;
                    s[snake[k].x][snake[k].y]='.';
                }
                else
                    s[snake[k].x][snake[k].y]='#';
            init();
            for (int dep=0; dep<=M; dep++)
                for (int i=0; i<N; i++)
                    for (int j=0; j<N; j++)
                    {
                        if (s[i][j]=='#') continue;
                        int sour=getPos(dep,i,j);
                        for (int k=0; k<4; k++)
                        {
                            int dx=i+dir[k][0];
                            int dy=j+dir[k][1];
                            if (check(dx,dy))
                            {
                                if(s[dx][dy]=='.'||s[dx][dy]=='T'||s[dx][dy]=='K')
                                {
                                    int dest=getPos(dep,dx,dy);
                                    addedge(sour,dest,1);
                                }
                                int res=unlock(dep,dx,dy);
                                if(res==1)
                                {
                                    int dest=getPos(dep,dx,dy);
                                    addedge(sour,dest,1);
                                }
                                else if(res==0)
                                {
                                    int dest=getPos(dep+1,dx,dy);
                                    addedge(sour,dest,1);
                                }
                            }
                        }
                    }
            int sp=getPos(0,sx,sy);
            spfa(sp);
            int ep=getPos(M,ex,ey);
            int res=dis[ep];
            if (res<INF)
                ans=min(ans,res+Kill);
        }
        if (ans<INF)
            printf("%d\n",ans);
        else
            printf("impossible\n");
    }
    return 0;
}
/*
3 1
K..
##1
1#T
*/


相關文章