ACM超时问题

版权声明:版权声明,使用请说明出处 https://blog.csdn.net/qq_41835683/article/details/82018564

  上次听学长说,关于标记数组最好换成布尔型的,节约空间时间,一直不以为然,直到做到Codeforces Round #442 (Div. 2)D. Olya and Energy Drinks的时候一直在44组测试数据超时,花了超长时间才发现是标记数组类型这里拉长了时间QAQ。这次一定记住了!!!(跟普通走迷宫的不同之处在于能走多步而已)

附上代码

#include <iostream>
#include <queue>
using namespace std;
const int maxn=1e3+10;
char arr[maxn][maxn];
bool book[maxn][maxn];
int dx[]={-1,0,1,0}, dy[]={0,-1,0,1};
int n, m, k;
int x1, y1, x2, y2;
struct node{
    int x, y;
    int step;
}temp;
queue<node>q;
int bfs(){
    if(x1==x2&&y1==y2){
        return 0;
    }
    temp.x=x1;
    temp.y=y1;
    temp.step=0;
    q.push(temp);
    book[x1][y1]=1;
    while(!q.empty()){
        temp=q.front();
        q.pop();
        int x=temp.x,y=temp.y,step=temp.step;
        for(int i=0;i<4;i++){
            for(int j=1;j<=k;j++){
                int nx=x+dx[i]*j;
                int ny=y+dy[i]*j;
                if(nx==x2&&ny==y2){
                    return step+1;
                }
                if(nx<0||nx>=n||ny<0||ny>=m||arr[nx][ny]=='#'){
					break;
				}
				if(book[nx][ny]==0){
					book[nx][ny]=1;
					temp.x=nx;
					temp.y=ny;
					temp.step=step+1;
					q.push(temp);
				}
            }
        }
    }
    return -1;
}
int main(){
    cin>>n>>m>>k;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        cin>>arr[i][j];
    cin>>x1>>y1>>x2>>y2;
    x1--;
    y1--;
    x2--;
    y2--;
    cout<<bfs()<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41835683/article/details/82018564