AtCoder:Infinite Sequence(dp)
阿新 • • 發佈:2019-02-03
F - Infinite Sequence
Time limit : 2sec / Memory limit : 256MB
Score : 1000 points
Problem Statement
How many infinite sequences a1,a2,… consisting of {1,…,n} satisfy the following conditions?
- The n-th and subsequent elements are all equal. That is, if n≤i,j, ai=aj.
- For every integer i, the ai elements
immediately following the i
Find the count modulo 109+7.
Constraints
- 1≤n≤106
Input
Input is given from Standard Input in the following format:
n
Output
Print how many sequences satisfy the conditions, modulo 109+7.
Sample Input 1
Copy2
Sample Output 1
Copy4
The four sequences that satisfy the conditions are:
- 1,1,1,…
- 1,2,2,…
- 2,1,1,…
- 2,2,2,…
Sample Input 2
Copy654321
Sample Output 2
Copy968545283題意:給定數字N,問有多少個長度無限的數列滿足如下要求:
各個元素範圍在[1,N],第i個元素後面a[i]個元素都要一樣,第N個元素及其往後的數字都一樣。
思路:發現1是比較特殊的一個數,定義dp[i]為空出前n-i個位置時的解,當第一個數字為1時,顯然dp[i] = dp[i-1],當第一個數字不為1且第二個數字不為1時,顯然數列為abbbbbb...形式,有(n-1)*(n-1)種,當第一個數字不為1且第二個數字為1時,有dp[i] += dp[i-3] + dp[i-4] +...+dp[1] + (n-i+2)種。
# include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL mod = 1e9+7;
LL dp[1000003];
int main()
{
LL n, sum=0;
scanf("%lld",&n);
dp[1] = n;
dp[2] = (n*n)%mod;
for(int i=3; i<=n; ++i)
{
sum = (sum + dp[i-3])%mod;
dp[i] = (dp[i-1] + sum + (n-1)*(n-1)%mod + n-i+2)%mod;
}
printf("%lld\n",dp[n]);
return 0;
}