ACM超時問題

  上次聽學長說,關於標記數組最好換成布爾型的,節約空間時間,一直不覺得然,直到作到Codeforces Round #442 (Div. 2)D. Olya and Energy Drinks的時候一直在44組測試數據超時,花了超長時間才發現是標記數組類型這裏拉長了時間QAQ。此次必定記住了!!!(跟普通走迷宮的不一樣之處在於能走多步而已)node

附上代碼

#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;
}
相關文章
相關標籤/搜索