现在的位置: 首页 > 综合 > 正文

hdu 1044 Collect More Jewels (两种解法 1.bfs+状压 2.bfs+dfs)

2012年06月29日 ⁄ 综合 ⁄ 共 6914字 ⁄ 字号 评论关闭

Collect More Jewels

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 3545    Accepted Submission(s): 703

Problem Description
It is written in the Book of The Lady: After the Creation, the cruel god Moloch rebelled against the authority of Marduk the Creator.Moloch stole from Marduk the most powerful of all the artifacts of the gods, the Amulet of Yendor,
and he hid it in the dark cavities of Gehennom, the Under World, where he now lurks, and bides his time.

Your goddess The Lady seeks to possess the Amulet, and with it to gain deserved ascendance over the other gods.

You, a newly trained Rambler, have been heralded from birth as the instrument of The Lady. You are destined to recover the Amulet for your deity, or die in the attempt. Your hour of destiny has come. For the sake of us all: Go bravely with The Lady!

If you have ever played the computer game NETHACK, you must be familiar with the quotes above. If you have never heard of it, do not worry. You will learn it (and love it) soon.

In this problem, you, the adventurer, are in a dangerous dungeon. You are informed that the dungeon is going to collapse. You must find the exit stairs within given time. However, you do not want to leave the dungeon empty handed. There are lots of rare jewels
in the dungeon. Try collecting some of them before you leave. Some of the jewels are cheaper and some are more expensive. So you will try your best to maximize your collection, more importantly, leave the dungeon in time.

 

Input
Standard input will contain multiple test cases. The first line of the input is a single integer T (1 <= T <= 10) which is the number of test cases. T test cases follow, each preceded by a single blank line.

The first line of each test case contains four integers W (1 <= W <= 50), H (1 <= H <= 50), L (1 <= L <= 1,000,000) and M (1 <= M <= 10). The dungeon is a rectangle area W block wide and H block high. L is the time limit, by which you need to reach the exit.
You can move to one of the adjacent blocks up, down, left and right in each time unit, as long as the target block is inside the dungeon and is not a wall. Time starts at 1 when the game begins. M is the number of jewels in the dungeon. Jewels will be collected
once the adventurer is in that block. This does not cost extra time.

The next line contains M integers,which are the values of the jewels.

The next H lines will contain W characters each. They represent the dungeon map in the following notation:
> [*] marks a wall, into which you can not move;
> [.] marks an empty space, into which you can move;
> [@] marks the initial position of the adventurer;
> [<] marks the exit stairs;
> [A] - [J] marks the jewels.

 

Output
Results should be directed to standard output. Start each case with "Case #:" on a single line, where # is the case number starting from 1. Two consecutive cases should be separated by a single blank line. No blank line should be
produced after the last test case.

If the adventurer can make it to the exit stairs in the time limit, print the sentence "The best score is S.", where S is the maximum value of the jewels he can collect along the way; otherwise print the word "Impossible" on a single line.

 

Sample Input
3 4 4 2 2 100 200 **** *@A* *B<* **** 4 4 1 2 100 200 **** *@A* *B<* **** 12 5 13 2 100 200 ************ *B.........* *.********.* *@...A....<* ************
 

Sample Output
Case 1: The best score is 200. Case 2: Impossible Case 3: The best score is 300.
 

Source
题意:走迷宫,告诉你起点和终点,还有几个宝物,问你在给定的l时间里,到达终点后所持到最大的珠宝价值是多少。
ps:这题有两种解法  一种是bfs+状态压缩  第二种是bfs+dfs 

思路(1):bfs+状态压缩   921MS 险过了   
vis[x][y][state] 判重   state为所有珠宝的状态   因为最多10种珠宝  故可以用 0~(1<<10) 以内的数来表示珠宝被拿的状态,记住同一个珠宝不能拿两次呦!我就被坑在这里了。

代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define maxn 51
using namespace std;

int n,m,l,cnt,ans;
int sx,sy,ex,ey;
int a[15];
int dx[]= {-1,1,0,0};
int dy[]= {0,0,-1,1};
bool vis[maxn][maxn][1<<10];
char s[maxn];
char mp[maxn][maxn];
struct Node
{
    int x,y,step,val;
    int state;
} cur,now;
queue<Node>q;

bool bfs()
{
    int i,j,nx,ny,tx,ty,nstep,nval,nst,tst,tmp;
    int head=0,tail=-1;
    memset(vis,0,sizeof(vis));
    while(!q.empty()) q.pop();
    ans=-1;
    cur.x=sx;
    cur.y=sy;
    cur.step=0;
    cur.val=0;
    cur.state=0;
    q.push(cur);
    vis[sx][sy][0]=1;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        nx=now.x;
        ny=now.y;
        nstep=now.step;
        nval=now.val;
        nst=now.state;
        if(nstep>l) break ;     // 注意退出条件
        if(nx==ex&&ny==ey)      // 更新ans
        {
            if(ans<nval) ans=nval;
        }
        for(i=0; i<4; i++)
        {
            tst=nst;
            tx=nx+dx[i];
            ty=ny+dy[i];
            cur.val=nval;
            if(mp[tx][ty]>='A'&&mp[tx][ty]<='J')
            {
                tmp=mp[tx][ty]-'A';
                if(!(tst&(1<<tmp))) cur.val+=a[tmp];   // 同一珠宝不能拿两次
                tst=tst|(1<<tmp);
            }
            if(tx>=1&&tx<=n&&ty>=1&&ty<=m&&mp[tx][ty]!='*'&&!vis[tx][ty][tst])
            {
                vis[tx][ty][tst]=1;
                cur.x=tx;
                cur.y=ty;
                cur.step=nstep+1;
                cur.state=tst;
                q.push(cur);
            }
        }
    }
    if(ans==-1) return false ;
    return true ;
}
int main()
{
    int i,j,t,t1=0;
    scanf("%d",&t);
    while(t--)
    {
        t1++;
        scanf("%d%d%d%d",&m,&n,&l,&cnt);
        for(i=0; i<cnt; i++)
        {
            scanf("%d",&a[i]);
        }
        for(i=1; i<=n; i++)
        {
            scanf("%s",s);
            for(j=1; j<=m; j++)
            {
                mp[i][j]=s[j-1];
                if(s[j-1]=='@')
                {
                    sx=i;
                    sy=j;
                }
                if(s[j-1]=='<')
                {
                    ex=i;
                    ey=j;
                }
            }
        }
        if(t1>1) printf("\n");
        printf("Case %d:\n",t1);
        if(bfs()) printf("The best score is %d.\n",ans);
        else printf("Impossible\n");
    }
    return 0;
}

思路(2): bfs+dfs  

对整个城堡做bfs,bfs求得某个点(其实包含3种,入口、出口、宝藏)到另外一个点(也是那3种)之间的最短路。bfs过程中构建隐式图,然后从入口处开始进行dfs搜索,更新ans。

感想:自己想的剪枝(感觉还是蛮强的剪枝)过不了,汗! 看了discuss上的代码,加了个剪枝就过了,优化到31ms了。
dfs剪枝:
1.step>time直接return。
2.ans==sum时就不用再搜了  因为已经到最大了。
3.如果搜到一个点,这个点以前已经搜过,而且现在到达这个点时珠宝价值比以前少而且走的步数却比以前多,就不用搜这个点了。(恩 说一下 我下面的代码中的int vv[15],vs[15]; 就是用来剪这个枝的  其实这个不用要也可以很快就过的)

代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define maxn 55
using namespace std;

int n,m,l,cnt,ans,sum;
int sx,sy,ex,ey;
int a[15];
int dx[]= {-1,1,0,0};
int dy[]= {0,0,-1,1};
bool vis[maxn][maxn];
char s[maxn];
char mp[maxn][maxn];
int dist[15][15];   // 构造隐式图 用来dfs 0~9代表A~J 10~@ 11~<
bool dvis[15];
int vv[15],vs[15];   
struct Node
{
    int x,y,step;
} cur,now;
queue<Node>q;

void bfs(int stx,int sty,int k)     // bfs找最短路
{
    int i,j,nx,ny,tx,ty,nstep,tmp;
    while(!q.empty()) q.pop();
    memset(vis,0,sizeof(vis));
    cur.x=stx;
    cur.y=sty;
    cur.step=0;
    q.push(cur);
    vis[stx][sty]=1;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        nx=now.x;
        ny=now.y;
        nstep=now.step;
        if(nstep>l) break ;
        if(nstep)
        {
            if(mp[nx][ny]>='A'&&mp[nx][ny]<='J')
            {
                tmp=mp[nx][ny]-'A';
                dist[k][tmp]=dist[tmp][k]=nstep;
            }
            else if(mp[nx][ny]=='@')
            {
                tmp=10;
                dist[k][tmp]=dist[tmp][k]=nstep;
            }
            else if(mp[nx][ny]=='<')
            {
                tmp=11;
                dist[k][tmp]=dist[tmp][k]=nstep;
            }
        }
        for(i=0; i<4; i++)
        {
            tx=nx+dx[i];
            ty=ny+dy[i];
            if(mp[tx][ty]!='*'&&!vis[tx][ty])
            {
                vis[tx][ty]=1;
                cur.x=tx;
                cur.y=ty;
                cur.step=nstep+1;
                q.push(cur);
            }
        }
    }
}
bool dfs(int k,int val,int step)   // dfs搜答案
{
    int i,j,flag=0;
    if(step>l||vv[k]>=val&&vs[k]<=step||ans==sum) return false;  
    if(k==11)
    {
        if(ans<val) ans=val;
        return true;
    }
    for(i=0;i<=11;i++)
    {
        if(dist[k][i]&&!dvis[i])
        {
            dvis[i]=1;
            if(dfs(i,val+a[i],step+dist[k][i]))
            {
                flag=1;
                if(vv[k]<val)
                {
                    vv[k]=val;
                    vs[k]=step;
                }
            }
            dvis[i]=0;
        }
    }
    if(flag) return true ;
    return false ;
}
int main()
{
    int i,j,t,t1=0;
    scanf("%d",&t);
    while(t--)
    {
        t1++;
        sum=0;
        scanf("%d%d%d%d",&m,&n,&l,&cnt);
        for(i=0; i<cnt; i++)
        {
            scanf("%d",&a[i]);
            sum+=a[i];
        }
        a[10]=a[11]=0;
        memset(mp,'*',sizeof(mp));
        memset(dist,0,sizeof(dist));
        for(i=1; i<=n; i++)
        {
            scanf("%s",s);
            for(j=1; j<=m; j++)
            {
                mp[i][j]=s[j-1];
                if(s[j-1]=='@') sx=i,sy=j;
                else if(s[j-1]=='<') ex=i,ey=j;
            }
        }
        for(i=1;i<=n;i++)   // 从每个点出发 找到这个点到其他点的最短路
        {
            for(j=1;j<=m;j++)
            {
                if(mp[i][j]=='@') bfs(i,j,10);
                else if(mp[i][j]=='<') bfs(i,j,11);
                else if(mp[i][j]>='A'&&mp[i][j]<='J') bfs(i,j,mp[i][j]-'A');
            }
        }
        if(t1>1) printf("\n");
        printf("Case %d:\n",t1);
        ans=-1;
        memset(dvis,0,sizeof(dvis));
        memset(vv,-1,sizeof(vv));  
        memset(vs,-1,sizeof(vs));   
        dvis[10]=1;
        dfs(10,0,0);
        if(ans!=-1) printf("The best score is %d.\n",ans);
        else printf("Impossible\n");
    }
    return 0;
}

抱歉!评论已关闭.