Skip to content

Instantly share code, notes, and snippets.

@shiponcs
Last active May 14, 2020 10:14
Show Gist options
  • Save shiponcs/18390822c65698edcd869448578edc44 to your computer and use it in GitHub Desktop.
Save shiponcs/18390822c65698edcd869448578edc44 to your computer and use it in GitHub Desktop.
Timus DP 1225-Flag
#include <iostream>
using namespace std;
using ull = unsigned long long;
int main()
{
int n;
cin >> n;
ull dp[n + 1][2]; // dp[i][0] i-th stripe ends with white
dp[1][0] = dp[1][1] = dp[2][0] = dp[2][1] = 1;
for(int i = 3; i <= n; i++){
dp[i][0] = dp[i - 1][1] + dp[i - 2][1];
dp[i][1] = dp[i - 1][0] + dp[i - 2][0];
}
cout << dp[n][0] + dp[n][1] << '\n';
return 0;
}
/*
dp[n][0] + dp[n][1] should return the answer for n;
recursive relation:
dp[n][0] = dp[n - 1][1] + dp[n - 2][1]
dp[n][1] = dp[n - 1][0] + dp[n - 2][1]
judgeID:249119DJ
*/
#include <iostream>
using namespace std;
using ull = unsigned long long;
int main()
{
int n;
cin >> n;
ull dp[n + 1];
dp[1] = dp[2] = 2;
for(int i = 3; i <= n; i++){
dp[i] = dp[i - 1] + dp[i - 2];
}
cout << dp[n] << '\n';
return 0;
}
@shiponcs
Copy link
Author

shiponcs commented Oct 30, 2019

First I solved with 2D array, latter I myself got to discover that my solution's recursive relation direct me to an easy approach using 1D array:
LooK:
answer for n = dp[n][0] + dp[n][1] = dp[n - 1][1] + dp[n - 2][1] + dp[n - 1][0] + dp[n - 2][1] never changes for different n.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment