Description
The area can be represented as a N*M rectangle. Any points of the rectangle is a number means the cost of research it,-1 means James can't cross it, James can start at any place out of the rectangle, and explore point next by next. He will move in the rectangle and bring out all treasures he can take. Of course, he will end at any border to go out of rectangle(James will research every point at anytime he cross because he can't remember whether the point are researched or not).
Now give you a map of the area, you must calculate the least cost that James bring out all treasures he can take(one point up to only one treasure).Also, if nothing James can get, please output 0.
Input
Output
Sample Input
2 3 3 3 2 3 5 4 3 1 4 2 1 1 1 3 3 3 2 3 5 4 3 1 4 2 2 1 1 2 2
Sample Output
8 11
hdu 4568 Hunter 最短路+dp
problem:
给你一个n*m的地图,每走一个格子会有一定的花费.求拿到所有宝藏的最小花费
solve:
想了很久感觉没什么思路TAT
后来看别人题解可以把这个问题转换一下.
因为总共只有13个宝藏,所以我们可以处理出每个宝藏之间的最短路(即最小花费).
在弄出每个宝藏到边界的最小距离. 那么就可以看成13个点的图.找出遍历所有点的最小花费
而13个点的状态可以用二进制保存,所以dp就好.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
const int N = 15;
const int M = 250;
const int inf = 0x3f3f3f3f;
typedef long long LL;
int dp[20][1<<N], tmap[M][M], tbao[M][M], from[M][M], out[M*M], dis[M*M], vis[M*M], pos[M*M];
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
int n, m;
void init()
{
memset(dp,inf,sizeof(dp));
memset(tbao,-1,sizeof(tbao));
memset(from,0,sizeof(from));
memset(out,inf,sizeof(out));
return ;
}
struct NODE
{
int id,len;
bool operator <(const NODE &a) const
{
return len > a.len;
}
};
void dij(int y1,int x1)
{
memset(vis,0,sizeof(vis));
memset(dis,inf,sizeof(dis));
priority_queue<NODE> q;
dis[y1]=0;
NODE e;
e.id=y1,e.len=dis[y1];
q.push(e);
while(!q.empty())
{
NODE cur=q.top();
q.pop();
int x=cur.id/m,y=cur.id%m;
if(vis[cur.id])
continue;
vis[cur.id]=1;
if(x==0||x==n-1||y==0||y==m-1)
out[x1]=min(dis[cur.id],out[x1]);
if(tbao[x][y]!=-1)
from[x1][tbao[x][y]]=dis[cur.id];
for(int i=0; i<4; i++)
{
int a=x+dir[i][0], b=y+dir[i][1];
if(a<0||a>=n||b<0||b>=m||tmap[a][b]==-1)
continue;
int tmp=a*m+b;
if(dis[tmp]>dis[cur.id]+tmap[a][b])
{
dis[tmp]=dis[cur.id]+tmap[a][b];
e.id=tmp,e.len=dis[tmp];
q.push(e);
}
}
}
return ;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
init();
int q;
scanf("%d %d", &n, &m);
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
scanf("%d",&tmap[i][j]);
}
}
scanf("%d", &q);
for(int i=0; i<q; i++)
{
int x, y;
scanf("%d %d",&x, &y);
tbao[x][y]=i;
pos[i]=x*m+y;
}
for(int i=0; i<q; i++)
{
from[i][i]=0;
dij(pos[i],i);
}
for(int i=0; i<q; i++)
{
dp[i][1<<i]=out[i]+tmap[pos[i]/m][pos[i]%m];
}
for(int i=0; i<(1<<q); i++)
{
for(int j=0; j<q; j++)
{
if(!(i&(1<<j))||i==(1<<j))
continue;
for(int k=0; k<q; k++)
{
if(k==j||(!(i&(1<<k)))||i==(1<<k))
continue;
dp[j][i]=min(dp[j][i],dp[k][i-(1<<j)]+from[k][j]);
}
}
}
int ans=inf;
for(int i=0; i<q; i++)
{
ans=min(ans,dp[i][(1<<q)-1]+out[i]);
}
printf("%d\n",ans);
}
return 0;
}