Hduoj2612【BFS】

来源:互联网 发布:少女前线数据库 编辑:程序博客网 时间:2024/06/05 09:41
/*Find a way Time Limit : 3000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)Total Submission(s) : 29   Accepted Submission(s) : 8Font: Times New Roman | Verdana | Georgia Font Size: ← →Problem DescriptionPass 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.InputThe 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.‘@’ KCFOutputFor 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 Input4 4Y.#@.....#..@..M4 4Y.#@.....#..@#.M5 5Y..@..#....#...@..M.#...#Sample Output668866Authoryifenfei Source奋斗的年代 */#include<stdio.h>#include<string.h>char s[205][205];int n, m,  min, dx[4] = {0, 0, 1, -1}, dy[4] = {1, -1, 0, 0}, x1, x2, y1, y2, d[205][205][2];//d用来保存YM到达同一个KFC分别需要的时间void bfs(int x, int y){int vis[205][205] = {0}, i, j, dis[205][205] = {0}, q[40010][2];int flag;if(x == x1 && y == y1)//分开保存2个起点到KFC的时间flag = 0;elseflag = 1;vis[x][y] = 1;int front = 0, rear = 0; q[rear][0] = x;q[rear++][1] = y;while(front < rear){x = q[front][0];y = q[front++][1];if(s[x][y] == '@')d[x][y][flag] = dis[x][y];for(i = 0; i < 4; ++i){int nx = x+dx[i], ny = y+dy[i];if(nx >= 0 && nx < n && ny >= 0 && ny < m && !vis[nx][ny] && s[nx][ny] != '#' ){vis[nx][ny] = 1;dis[nx][ny] = dis[x][y] + 11;q[rear][0] = nx;q[rear++][1] = ny;}}}}int main(){int i, j, k, num, start[40010][2];while(scanf("%d%d", &n, &m) != EOF){getchar();num = 0;for(i = 0; i < n; ++i){for(j = 0; j < m; ++j)//记录YM和KFC的坐标{scanf("%c", &s[i][j]);if(s[i][j] == '@'){start[num][0] = i;start[num++][1] = j;}if(s[i][j] == 'Y'){x1 = i;y1 = j;}if(s[i][j] == 'M'){x2 = i;y2 = j;}}getchar();}memset(d,  0, sizeof(d));//初始化min = 100000000;bfs(x1, y1);bfs(x2, y2);for(i = 0; i < num; ++i)//遍历所有KFC找到最小的时间{if(d[start[i][0]][start[i][1]][0] != 0 && d[start[i][0]][start[i][1]][1] != 0){if(d[start[i][0]][start[i][1]][0] + d[start[i][0]][start[i][1]][1] < min)min = d[start[i][0]][start[i][1]][0] + d[start[i][0]][start[i][1]][1];}}printf("%d\n", min);}return 0;}


题意:Y和M要见面,约定在KFC见面,但是有很多个KFC,现在给你YM和KFC的地图,求他们到达KFC所需要的最小时间。

思路:用的就是BFS,这里需要分别对Y和M进行BFS,分别找出他们到达KFC的时间。值得注意的是,保存的细节,还有这里MY两个点可以看做是可以走的,也可以看做是不能走的。貌似对AC没什么影响。

0 0