HDU 2 612?Find a way 題意就是在圖中找一條最短路徑使得 Y M到一家kfc(@)約會,求出約會最短的路徑 @可能有多家,#是障礙物 各種Exceeded得姿勢,先是用的pair導致得是TLE,改了之后又MLE,之后又回到TLE, 最終倆個TLE一個是pair還有一個是vis標記得時候在進度隊列的時候進行標記得話,相對來說會減少很多次進隊次數
#include <cstdio>
#include <iostream>
#include <queue>
#include <bits/stdc++.h>
#include <cstring>
using namespace std;
const int inf=99999;
int n,m;
char mp[201][201];
int step[201][201][2];
int vis[201][201];
int dir[4][2]={{1,0},{0,1},{0,-1},{-1,0}};
int flag;
struct node{
int x,y;};
void bfs(int x,int y){queue<node >q;node p,tmp;//pair<int,int> p;p.x=x,p.y=y;q.push(p);while(!q.empty()){p=q.front();q.pop();//int x=p.x;//int y=p.y;//vis[p.x][p.y]=1;for(int i=0;i<4;++i){tmp.x=p.x+dir[i][0];tmp.y=p.y+dir[i][1];if(tmp.x<0||tmp.x>=n||tmp.y<0||tmp.y>=m||vis[tmp.x][tmp.y]||mp[tmp.x][tmp.y]=='#')continue;step[tmp.x][tmp.y][flag]=step[p.x][p.y][flag]+1;q.push(tmp);vis[tmp.x][tmp.y]=1;}}
}
int main(){while(scanf("%d%d",&n,&m)!=EOF){for(int i=0;i<n;++i)scanf("%s",mp[i]);memset(step, inf,sizeof(step));for(int i=0;i<n;++i)for(int j=0;j<m;++j){if(mp[i][j]=='Y'){memset(vis,0,sizeof(vis));flag=0;step[i][j][flag]=0;bfs(i,j);}if(mp[i][j]=='M'){memset(vis,0,sizeof(vis));flag=1;step[i][j][flag]=0;bfs(i,j);}}int dis=inf;for(int i=0;i<n;++i)for(int j=0;j<m;++j){if(mp[i][j]=='@'&&dis>step[i][j][0]+step[i][j][1]){dis=step[i][j][0]+step[i][j][1];//dis=min(dis,step[i][j][0]+step[i][j][1]);}}printf("%d\n",dis*11);}return 0;
}
//MLE&&TLE:
#include <cstdio>
#include <iostream>
#include <queue>
#include <bits/stdc++.h>
#include <cstring>
using namespace std;
const int inf=0x3f3f3f3f;
int n,m;
char mp[220][220];
int step[220][220][2];
int vis[220][220];
int dir[4][2]={{1,0},{0,1},{0,-1},{-1,0}};
int flag;
void bfs(int x,int y){queue<pair<int,int> >q;pair<int,int> p;q.push(make_pair(x,y));while(!q.empty()){p=q.front();q.pop();int x=p.first;int y=p.second;for(int i=0;i<4;++i){int dx=x+dir[i][0];int dy=y+dir[i][1];if(dx<1||dx>n||dy<1||dy>m||vis[dx][dy]||mp[dx][dy]=='#')continue;step[dx][dy][flag]=step[x][y][flag]+1;q.push(make_pair(dx,dy));vis[x][y]=1;}}
}
int main(){while(scanf("%d%d",&n,&m)!=EOF){for(int i=1;i<=n;++i)scanf("%s",mp[i]+1);memset(step, inf,sizeof(step));for(int i=1;i<=n;++i)for(int j=1;j<=m;++j)step[i][j][0]=step[i][j][1]=inf;for(int i=1;i<=n;++i)for(int j=1;j<=m;++j){if(mp[i][j]=='Y'){memset(vis,0,sizeof(vis));flag=0;step[i][j][flag]=0;bfs(i,j);}if(mp[i][j]=='M'){memset(vis,0,sizeof(vis));flag=1;step[i][j][flag]=0;bfs(i,j);}}int dis=inf;for(int i=1;i<=n;++i)for(int j=1;j<=m;++j){if(mp[i][j]=='@'){dis=min(dis,step[i][j][0]+step[i][j][1]);}}printf("%d\n",dis*11);}return 0;
}