标签:
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....<* ************
Case 1: The best score is 200. Case 2: Impossible Case 3: The best score is 300.
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
char a[55][55];//地图
int dis[55][55];//起点,珠宝,出口之间的距离
int step[55][55];//
bool vis[55][55];//BFS标记
bool mark[55];//DFS标记
int val[55];//珠宝价值
int w,h,t,n;
int sum,ans;
int dir[4][2]={1,0,0,1,-1,0,0,-1};
bool OK(int x,int y)
{
if(x<0||x>=h||y<0||y>=w)
return false;
return true;
}
void BFS(int x,int y,int idx)
{
queue<int>q;
while(!q.empty())
q.pop();
memset(step,0,sizeof(step));
memset(vis,false,sizeof(vis));
step[x][y]=0;
vis[x][y]=true;
int p=x*w+y;
q.push(p);
while(!q.empty())
{
p=q.front();
q.pop();
int x=p/w;
int y=p%w;
for(int i=0;i<4;i++)
{
int xx=x+dir[i][0];
int yy=y+dir[i][1];
if(OK(xx,yy)&&!vis[xx][yy]&&a[xx][yy]!='*')
{
vis[xx][yy]=true;
step[xx][yy]=step[x][y]+1;
if(a[xx][yy]=='@')
dis[idx][0]=step[xx][yy];
else if(a[xx][yy]=='<')
dis[idx][n+1]=step[xx][yy];
else if(a[xx][yy]>='A'&&a[xx][yy]<='J')
dis[idx][a[xx][yy]-'A'+1]=step[xx][yy];
q.push(xx*w+yy);
}
}
}
}
//当前收集珠宝价值,当前珠宝价值,消耗时间
void DFS(int s,int value,int time)
{
//注意下面三条语句的顺序
if(time>t)
return;
if(ans==sum)
return;
if(s>n)
{
if(value>ans)
ans=value;
return;
}
for(int i=0;i<=n+1;i++)
{
if(mark[i]||dis[s][i]==0)
continue;
mark[i]=true;
DFS(i,value+val[i],time+dis[s][i]);
mark[i]=false;
}
}
int main()
{
int T,kase=0;
cin>>T;
while(T--)
{
cin>>w>>h>>t>>n;
sum=0;
for(int i=1; i<=n; i++)
{
cin>>val[i];
sum+=val[i];
}
val[0]=val[n+1]=0;
//把起点和终点当做第一个和最后一个价值为0珠宝
for(int i=0; i<h; i++)
cin>>a[i];
memset(dis,0,sizeof(dis));
for(int i=0; i<h; i++)
{
for(int j=0; j<w; j++)
{
if(a[i][j]=='@')
BFS(i,j,0);
else if(a[i][j]=='<')
BFS(i,j,n+1);
else if(a[i][j]>='A'&&a[i][j]<='J')
BFS(i,j,a[i][j]-'A'+1);
}
}
memset(mark,false,sizeof(mark));
mark[0]=true;
ans=-1;
DFS(0,0,0);
cout<<"Case "<<++kase<<":"<<endl;
if(ans>=0)
cout<<"The best score is "<<ans<<"."<<endl;
else
cout<<"Impossible"<<endl;
if(T)
cout<<endl;
}
return 0;
}
HDU 1044 Collect More Jewels 【经典BFS+DFS】
标签:
原文地址:http://blog.csdn.net/hurmishine/article/details/51933805