강의

멘토링

커뮤니티

Inflearn Community Q&A

jsid15615489's profile image
jsid15615489

asked

Introduction to Algorithm Problem Solving for IT Employment (with C/C++): Coding Test Preparation

71. Finding the Calf (BFS: State Tree Search)

거리배열을 따로 만드는 경우 타임리밋

Written on

·

277

0

안녕하세요. 수업 잘 듣고 있습니다.

체크배열에 정점까지 도달하는 데 필요한 횟수를 저장하는 게 헷갈려서, dis배열을 따로 만들어봤습니다.

그랬더니 타임리밋이 걸리더라고요.

제가 보기엔 연산 속도에 큰 차이가 날 것 같지 않은데,

이렇게 배열 두 개를 사용할 경우 타임리밋이 걸리는 이유가 궁금합니다.

#include <stdio.h> 
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

int ch[10001], dis[10001], d[3]={1, -1, 5};

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

	int i, n, m, x, pos;
	queue<int> Q;
	
	scanf("%d %d", &n, &m);
	
	ch[n] = 1;
	Q.push(n);
	
	while(!Q.empty()){
		x = Q.front();
		Q.pop();
		
		for(i=0; i<3; i++){
			pos = x+d[i];
			if(pos<= 0 || pos>10000) continue;
			
			if(ch[pos]==0){
				dis[pos] = dis[x] + 1;
				Q.push(pos);
			}
			
			if(pos==m){
				printf("%d", dis[pos]);
				exit(0);
			}
		}
		
	}
	return 0;
}

C++코테 준비 같이 해요!

Answer 1

0

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

체크를 해서 한 번 방문한 곳은 다시 큐에 넣지 않기 위해서인데 그게 빠졌습니다.

ch[pos]=1; 

추가해야 합니다.

J Kim님의 프로필 이미지
J Kim
Questioner

체크하는 걸 까먹었네요. 

해결했습니다. 감사합니다 !! 

jsid15615489's profile image
jsid15615489

asked

Ask a question