알고리즘
백준 15990번 1, 2, 3 더하기 5 C++
영춘권의달인
2022. 11. 19. 12:43
https://www.acmicpc.net/problem/15990
15990번: 1, 2, 3 더하기 5
각 테스트 케이스마다, n을 1, 2, 3의 합으로 나타내는 방법의 수를 1,000,000,009로 나눈 나머지를 출력한다.
www.acmicpc.net
다이나믹 프로그래밍
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
const int64 mod = 1000000009;
vector<vector<int64>> cache;
int64 dp(int n, int lastN) {
if (n <= 0) return 0;
int64& val = cache[n][lastN];
if (val != -1) return val;
val = 0;
for (int i = 1; i <= 3; i++) {
if (lastN == i) continue;
val += dp(n - lastN, i);
}
val %= mod;
return val;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
cache = vector<vector<int64>>(100001, vector<int64>(4, -1));
cache[1][1] = 1;
cache[2][2] = 1;
cache[3][1] = 1;
cache[3][2] = 1;
cache[3][3] = 1;
while (t--) {
int n;
cin >> n;
int64 ans = dp(n, 1) + dp(n, 2) + dp(n, 3);
ans %= mod;
cout << ans << "\n";
}
}