您的位置:首页 > 其它

hdu 1044 Collect More Jewels(BFS+DFS)

2015-10-24 00:37 381 查看
原题链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1044
题目大意:

T组测试数据

W宽H高L时间限制M多少个宝石

m1……mM 宝石的价值

W*H矩阵

在限制时间内,从‘@’到‘<'且能获得的最大价值。

思路:

BFS:

求出任意两点之间的最短距离(含’@‘与’<')。

DFS:

求最大价值。

1.注意DFS时剪枝

2.注意初始化

详见代码;

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#include<utility>
#include<cstring>
using namespace std;
const int MAXN=55;
const int N=15;
int W,H,L,M;

bool vis
;
int value
;
int dis

;//0编号为起点M+1编号为终点 1-M为宝石

bool flog[MAXN][MAXN];
char G[MAXN][MAXN];//图

const int nextpos[][2]={{-1,0},{1,0},{0,-1},{0,1}};

typedef pair<int,int>ii;//first存位置second存耗费了多少个单位时间

int maxValue,ans;

bool check(int x,int y)//判断是否能走到下一个位置
{
if(x<0||x>=H||y<0||y>=W||flog[x][y]||G[x][y]=='*')
return false;
return true;
}

void BFS(int x,int y,int ch)
{
queue <ii> q;
memset(flog,0,sizeof(flog));

ii pos;
pos.first=x*W+y;
pos.second=0;
q.push(pos);
flog[x][y]=true;
while(!q.empty())
{
pos=q.front();
q.pop();
int nowx=pos.first/W;
int nowy=pos.first%W;
if(G[nowx][nowy]=='@')
dis[ch][0]=pos.second;
else if(G[nowx][nowy]=='<')
dis[ch][M+1]=pos.second;
else if(G[nowx][nowy]>='A'&&G[nowx][nowy]<='J')
dis[ch][G[nowx][nowy]-'A'+1]=pos.second;
for(int i=0;i<4;i++)
{
int tempx=nowx+nextpos[i][0];
int tempy=nowy+nextpos[i][1];
if(check(tempx,tempy))
{
ii temppos;
temppos.first=tempx*W+tempy;
temppos.second=pos.second+1;
flog[tempx][tempy]=true;
q.push(temppos);
}
}
}
}

void DFS(int u,int nowvalue,int nowt)//位置,价值,时间
{
if(nowt>L||ans==maxValue) return;//超时或已能得到最大价值
if(u>M)
{
if(nowvalue>ans) ans=nowvalue;
return;
}
for(int v=1;v<=M+1;v++)
{
if(vis[v]||dis[u][v]==0)
continue;
vis[v]=true;
DFS(v,nowvalue+value[v],nowt+dis[u][v]);
vis[v]=false;
}
}

int main()
{
int kase;
scanf("%d",&kase);
for(int k=1;k<=kase;k++)
{
memset(dis,0,sizeof(dis));
scanf("%d%d%d%d",&W,&H,&L,&M);
maxValue=0;

for(int i=1;i<=M;i++)
{
scanf("%d",&value[i]);
maxValue+=value[i];
}

value[M+1]=0;//勿忘初始化

for(int i=0;i<H;i++)
scanf("%s",G[i]);

for(int i=0;i<H;i++)
{
for(int j=0;j<W;j++)
{
if(G[i][j]=='@') BFS(i,j,0);
else if(G[i][j]=='<') BFS(i,j,M+1);
else if(G[i][j]>='A'&&G[i][j]<='J') BFS(i,j,G[i][j]-'A'+1);
}
}

memset(vis,0,sizeof(vis));
vis[0]=true;
ans=-1;
DFS(0,0,0);

if(k!=1)
printf("\n");
printf("Case %d:\n",k);
if(ans>=0)
printf("The best score is %d.\n",ans);
else printf("Impossible\n");

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: