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-th element are all equal. That is, if i<j<k≤i+ai, aj=ak.
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
Copy
2
Sample Output 1
Copy
4
The four sequences that satisfy the conditions are:
- 1,1,1,…
- 1,2,2,…
- 2,1,1,…
- 2,2,2,…
Sample Input 2
Copy
654321
Sample Output 2
Copy
968545283
各个元素范围在[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;
}