本文主要是介绍find a way HDU-2612,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Pass a year learning in Hangzhou, yifenfei arrival hometown Ningbo at finally. Leave Ningbo one year, yifenfei have many people to meet. Especially a good friend Merceki.
Yifenfei’s home is at the countryside, but Merceki’s home is in the center of city. So yifenfei made arrangements with Merceki to meet at a KFC. There are many KFC in Ningbo, they want to choose one that let the total time to it be most smallest.
Now give you a Ningbo map, Both yifenfei and Merceki can move up, down ,left, right to the adjacent road by cost 11 minutes.
Input
The input contains multiple test cases.
Each test case include, first two integers n, m. (2<=n,m<=200).
Next n lines, each line included m character.
‘Y’ express yifenfei initial position.
‘M’ express Merceki initial position.
‘#’ forbid road;
‘.’ Road.
‘@’ KCF
Output
For each test case output the minimum total time that both yifenfei and Merceki to arrival one of KFC.You may sure there is always have a KFC that can let them meet.
Sample Input
4 4
Y.#@
…
.#…
@…M
4 4
Y.#@
…
.#…
@#.M
5 5
Y…@.
.#…
.#…
@…M.
#…#
Sample Output
66
88
66
题意: 这道题是“Y”和“M”两个人决定在“@”地点集合,求两个人最少花费多少时间,每走一格花费11分钟。
思路: 这道题用到了广搜,即分别从“Y”和“M”进行搜索,记录两个人到达同一个“@”的时间,输出最短时间即可。
代码:
#include<stdio.h>
#include<string.h>
int n,m,p;
int d[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
int book[1010][1010];
char a[1010][1010];
int b[1010][1010];
int c[1010][1010];
struct node
{int x;int y;int step;
} s[10010];
void dfs(int x,int y)
{int tail=0,head=0,pp=0;s[tail].x=x;s[tail].y=y;s[tail].step=0;book[x][y]=1;tail++;while(head<tail){if(a[s[head].x][s[head].y]=='@'){pp++;b[s[head].x][s[head].y]+=s[head].step;c[s[head].x][s[head].y]++;}if(pp==p)break;for(int i=0; i<4; i++){int tx=s[head].x+d[i][0];int ty=s[head].y+d[i][1];if(tx<0||ty<0||tx>=n||ty>=m||book[tx][ty]||a[tx][ty]=='#')continue;book[tx][ty]=1;s[tail].x=tx;s[tail].y=ty;s[tail].step=s[head].step+1;tail++;}head++;}
}
int main()
{while(~scanf("%d%d",&n,&m)){int i,j;for(i=0; i<n; i++)scanf("%s",a[i]);p=0;for(i=0; i<n; i++)for(j=0; j<m; j++)if(a[i][j]=='@')p++;int x1,x2,y1,y2;for(i=0; i<n; i++){for(j=0; j<m; j++){if(a[i][j]=='Y'){x1=i;y1=j;}if(a[i][j]=='M'){x2=i;y2=j;}}}memset(c,0,sizeof(c));memset(b,0,sizeof(b));memset(book,0,sizeof(book));book[x1][y1]=1;dfs(x1,y1);//从“Y"搜索,记录”Y“到达每个”@“的时间memset(book,0,sizeof(book));book[x2][y2]=1;dfs(x2,y2);//从”M“搜索,记录”M“到达每个”@“的时间int sum,max=3421423;for(i=0; i<n; i++){for(j=0; j<m; j++){if(b[i][j]>0&&c[i][j]==2)//用b数组记录”Y“和”M“到达每个”@“的时间之和,c数组代表每个”@被搜到的次数,必须被搜到两次。{sum=b[i][j];if(sum<max)max=sum;}}}printf("%d\n",max*11);}return 0;
}
这篇关于find a way HDU-2612的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!