hdu--2612(两个起点遍历)

Find a way

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7838    Accepted Submission(s): 2559


Problem Description
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且经过@的第一个满足条件的情况是最优的,但要这样做bfs()中必须取消标记,结构当然是超内存了哭。第三次写,ac了,两个起点,第一个起点出发记录所有到@的最小时间,第二个起点出发,到达@时,先判断第一次是否到达过,再比较是否小于当前时间sum,最后得到的sum就是所求结果。
代码如下:
#include<stdio.h>
#include<queue>
#include<string.h>
#define INF 0x3f3f3f3f
using namespace std;
char mark[210][210];
char g[210][210];
int dis[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
int n,m,sum;
struct stu{
	int x,y,t;
};
int vist[210][210];
bool check(stu temp){
	if(temp.x<0||temp.y<0||temp.x>=n||temp.y>=m)return false;
	if(mark[temp.x][temp.y]=='#')return false;
	return true;
}
void  bfs(int x,int y,int flag){
	queue<stu>q;
	memcpy(mark,g,sizeof(mark));
	mark[x][y]='#';
	while(!q.empty()){
		q.pop();
	}
	stu temp,star;
	temp.x=x;temp.y=y;temp.t=0;
	q.push(temp);
	while(!q.empty()){
		star=q.front();
		q.pop();
		for(int i=0;i<4;i++){
			temp.x=star.x+dis[i][0];
			temp.y =star.y+dis[i][1];
			if(check(temp)){
				temp.t=star.t+11;
				if(mark[temp.x][temp.y]=='@'){
					if(!flag){
						vist[temp.x][temp.y]=temp.t;
					}
					else if(vist[temp.x][temp.y]){
						 vist[temp.x][temp.y]+=temp.t;
						 if(vist[temp.x][temp.y]<sum)
						 sum=vist[temp.x][temp.y];
					}
				}
				mark[temp.x][temp.y]='#';
				q.push(temp);
			}
		}
	}
	
}
int main(){
	int x1,y1,x2,y2;
	while(scanf("%d%d",&n,&m)!=EOF){
		for(int i=0;i<n;i++){
			getchar();
			for(int j=0;j<m;j++){
				scanf("%c",&g[i][j]);
				if(g[i][j]=='Y'){
				     x1=i;y1=j;
				}
				if(g[i][j]=='M'){
					x2=i;y2=j;
				}
			}
		}
		sum=INF;
		memset(vist,0,sizeof(vist));
		bfs(x1,y1,0);
		bfs(x2,y2,1);
		printf("%d\n",sum);
	}
	return 0;
}


 

你可能感兴趣的:(hdu--2612(两个起点遍历))