hihocoder-1732-1 - Bias permutation
#1732 : 1-bias permutation
describe
If any element Pi in a 1~N permutation P=[P1, P2, ... PN] satisfies |Pi-i| ≤ 1, we call P a 1-bias permutation.
Given an N, please calculate how many different permutations are 1-bias permutations.
For example for N=3, there are 3 1-bias permutations: [1, 2, 3], [1, 3, 2], [2, 1, 3].
enter
an integer N.
For 50% of the data, 1 ≤ N ≤ 15
For 100% of the data, 1 ≤ N ≤ 50
output
an integer representing the answer
- sample input
-
3
- Sample output
-
3
Find the law, a number i can only exist in the three positions i-1, i, i+1.
dp[n][0] indicates the number of legal array types with n at position n, dp[n][1] indicates the number of legal array types with n at position n-1 and n at position n-1
For an array of original n elements, to insert an n+1, there are two insertion methods,
Put it at position n+1, then dp[n+1][0] = dp[n][0] + dp[n][1];
Put it at position n-1, then dp[n+1][1] = dp[n][0];
The sequence of such numbers is the Fibonacci sequence. f[n] = f[n-1] + f[n-2]; a simplified version of this.
#include <cstdio> #include <cstdlib> const int MAXN = 100 + 10; int n; long long ans, dp[MAXN][2]; void init(){ dp[1][0] = 1; dp[1][1] = 0; for(int i=2; i<MAXN; ++i){ dp[i][0] = dp[i-1][0] + dp[i-1][1]; dp[i][1] = dp[i-1][0]; } } int main(){ init(); while(scanf("%d", &n) != EOF){ ans = dp[n][0] + dp[n][1]; printf("%lld\n", ans ); } return 0; }