題目鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=2416
Treasure of the Chimp Island
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 306 Accepted Submission(s): 148
Problem Description
The hardness of the stone blocks is an integer between 1 and 9, showing the number of days required to destroy the block. We neglect the time required to travel inside the corridors. Using a dynamite, Bob can destroy a block almost immediately, so we can ignore the time required for it too. The problem is to find the minimum time at which Bob can reach the treasure. He may choose any gate he wants to enter ZM2.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define INF 9999999
using namespace std;
struct data
{
int x,y;
int bomb;
int cost;
};
int row;
int col;
char mp[105][105];
int vis[105][105][26];
int result = INF;
int dir[4][2]= {0,1,1,0,-1,0,0,-1};
/*
bool operator<(data a,data b)
{
return a.cost>b.cost;
}
*/
void bfs()
{
memset(vis,-1,sizeof(vis));
int i,j;
data f;
queue <data> qu;
//入口
for( i =0; i<row; i++)
{
for(j=0; j<col; j++)
{
if(mp[i][j]=='#' || (mp[i][j]>='A' && mp[i][j]<='Z'))
{
f.x=i;
f.y=j;
f.cost=0;
if(mp[i][j]=='#') f.bomb=0;
else f.bomb = mp[i][j]-'A'+1;
qu.push(f);
vis[i][j][f.bomb]=0;
mp[i][j]='*';
}
}
}
//搜索
while(!qu.empty())
{
data e;
f = qu.front();
qu.pop();
for(i=0; i<4; i++)
{
e.x = f.x+dir[i][0];
e.y = f.y+dir[i][1];
if(mp[e.x][e.y]=='*' || e.x<0 || e.y<0 || e.x>=row || e.y>= col)
continue;
if(mp[e.x][e.y]=='.') //直接走過,時間不變,炸彈數不變
{
e.bomb=f.bomb;
if(vis[e.x][e.y][e.bomb] == -1 || f.cost < vis[e.x][e.y][e.bomb])
{
e.cost = f.cost;
vis[e.x][e.y][e.bomb] = f.cost;
qu.push(e);
}
}
else if(mp[e.x][e.y]>='1' && mp[e.x][e.y]<='9')
{
//不炸,炸彈不變,時間加上mp[e.x][e.y]
if(vis[e.x][e.y][f.bomb]==-1 || f.cost+mp[e.x][e.y]-'0' < vis[e.x][e.y][f.bomb])
{
e.bomb = f.bomb;
e.cost = f.cost + mp[e.x][e.y]-'0';
vis[e.x][e.y][e.bomb]=e.cost;
qu.push(e);
}
//炸,炸彈數-1,時間不變;
if(f.bomb>0)
{
if(vis[e.x][e.y][f.bomb-1]==-1 || f.cost < vis[e.x][e.y][f.bomb-1])
{
e.bomb = f.bomb - 1;
e.cost = f.cost;
vis[e.x][e.y][e.bomb]=e.cost;
qu.push(e);
}
}
}
/*else if(mp[e.x][e.y]=='$'&&f.cost<result)
result = f.cost;*/
else if(mp[e.x][e.y]=='$' && result > f.cost) //這個地方我找了一下午= =,找到$後,花費應該是前一步的,如果改成e.cost,則結果始終是0;
result = f.cost;
}
}
}
int main()
{
while(1)
{
row=0;
while(gets(mp[row]))
{
if(mp[row][0]=='-')
return 0;
if(strlen(mp[row])<1)
break;
row++;
}
col=strlen(mp[0]);
result=INF;
bfs();
if(result==INF) printf("IMPOSSIBLE\n");
else printf("%d\n",result);
}
return 0;
}