• 카테고리

    질문 & 답변
  • 세부 분야

    알고리즘 · 자료구조

  • 해결 여부

    미해결

왜 DP로 풀어야하는지 궁금합니다

22.09.09 13:47 작성 조회수 151

0

DFS 풀이는 시간초과가 발생하는 이유가 궁금합니다.

DFS 풀이는 시간초과가 발생하기 때문에 DP로 풀어야하는건가요?

이에 대한 설명은 없어서 질문드립니다.

 

 

 

DFS 시간초과 코드는 다음과 같았습니다.

struct Work {
	int s, e;
	int score;
};
int n, m, r;
vector<Work> schedule;
int result = 0;

bool compare(Work a, Work b) {
        return a.s < b.s;
}

void dfs(int now, int start, int score) {
	if (now >= n) {
		result = max(result, score);
		return;
	}
	result = max(result, score);

	for (int i = start; i < m; i++) {
		if (schedule[i].s < now) continue;
		dfs(schedule[i].e + r, i + 1, score + schedule[i].score);
	}
}

int main() {
	cin >> n >> m >> r;
	for (int i = 0; i < m; i++) {
		int s, e, score;
		cin >> s >> e >> score;
		schedule.push_back({ s,e,score });
	}
	sort(schedule.begin(), schedule.end(), compare);
	dfs(0, 0, 0);
	cout << result;
	return 0;
}

답변 1

답변을 작성해보세요.

0

안녕하세요^^

어찌보면 뻔한 말이라서 좀 그렇지만,

DFS는 모든 경우를 다 직접 해봐야 하는 알고리즘이고, 다이나믹은 이미 구해진 해을 이용하 다음 해를 다 해보지 않고 하는 방식이라 그렇습니다.