• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

선생님, 89번 토마토 문제 마지막 캐이스에서 시간초과가 됩니다.

21.01.31 00:49 작성 조회수 163

0

선생님,  안익은 토마토 개수를 세고 그 갯수를 빼가면서 다 익었는지 안익었는지를 검사하고 큐에 하루마다 -1을 집어넣어서 날짜를 셌습니다.  그런데 나머진 다 되도 마지막 문제만 시간초과가됩니다. 어디서 뭐 때문에 느려진 것인지 알 수 있을까요??

#include <cstdio>
#include <queue>

using std::pair;

int main(){
    //freopen("input.txt", "r", stdin);

    int n, m, tomatocnt = 0, pre = 0, now = 1, day = 0, tox, toy;;
    short map[1002][1002];
    std::queue<pair<int, int>> ripentomato;

    scanf("%d%d",&n, &m);
    for(int i = 1; i <= m; i++){
        for(int j = 1; j <= n; j++){
            scanf("%d", map[i]+j);
            
            if(map[i][j] == 0)++tomatocnt;
            else if(map[i][j] == 1)ripentomato.push(pair<int,int>(j,i));
        }
    }

    for(int i = 0; i <= n+1; i++)map[0][i] = map[m+1][i] = -1;
    for(int i = 0; i <= m+1; i++)map[i][0] = map[i][n+1] = -1;

    int move[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};
    pair<int,int> temp;

    while(tomatocnt){
        ripentomato.push(std::make_pair(-1,-1));
        while(true){
            temp = ripentomato.front();
            ripentomato.pop();
            
            if(temp.first == -1)break;

            for(int i = 0; i < 4; i++){
                tox = temp.first+move[i][0];
                toy = temp.second+move[i][1];

                if(map[toy][tox] == 0){
                    ripentomato.push(pair<int,int>(tox, toy));
                    map[toy][tox] = 1;
                    --tomatocnt;

                }
            }
        }

        if(ripentomato.empty()){
            printf("-1");
            return 0;
        }

        ++day;
    }
    
    printf("%d", day);

    return 0;
}

답변 1

답변을 작성해보세요.

0

forcommang님의 프로필

forcommang

질문자

2021.01.31

ios_base::sync_with_stdio(false); 써서 입력 받으니깐 되긴 하네요;;