※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 6844번 문제인 Keep on Truckin'이다.
문제는 아래 링크를 확인하자.

https://www.acmicpc.net/problem/6844 

 

6844번: Keep on Truckin’

A truck driver is planning to drive along the Trans-Canada highway from Vancouver to St. John’s, a distance of 7000 km, stopping each night at a motel. The driver has been provided with a list of locations of eligible motels, with the respective distance

www.acmicpc.net

각 모텔에 도달할 수 있는 경우의 수는 해당 모텔에서 음의 방향으로 폐구간 [A,B]에 속한 수만큼 떨어진 각 모텔들까지 도달할 수 있는 경우의 수의 합과 같음을 관찰하자.

 

위의 관찰을 이용하면 문제를 해결하는 DP 알고리즘을 간단히 고안해낼 수 있다. 이를 구현해주자.

 

아래는 제출한 소스코드이다.

#include <iostream>
using namespace std;
typedef long long ll;

int A, B, N;
int motel[14001];
ll dp[14001];

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	dp[0] = 1;
	motel[0] = motel[990] = motel[1010] = motel[1970] = motel[2030] = motel[2940] = motel[3060] = motel[3930] = motel[4060] = motel[4970] = motel[5030] = motel[5990] = motel[6010] = motel[7000] = 1;

	cin >> A >> B >> N;
	while (N--) {
		int x; cin >> x;
		motel[x] = 1;
	}

	for (int i = 0; i < 7000; i++) {
		if (!motel[i]) continue;
		for (int k = A; k <= B; k++) {
			dp[i + k] += dp[i];
		}
	}

	cout << dp[7000];
}
728x90

+ Recent posts