Ayoub had an array a of integers of size n and this array had two interesting properties:
All the integers in the array were between l and r (inclusive).
The sum of all the elements was divisible by 3.
Unfortunately, Ayoub has lost his array, but he remembers the size of the array n and the numbers l and r, so he asked you to find the number of ways to restore the array.
Since the answer could be very large, print it modulo 109+7 (i.e. the remainder when dividing by 109+7). In case there are no satisfying arrays (Ayoub has a wrong memory), print 0.
Input
The first and only line contains three integers n, l and r (1≤n≤2⋅105,1≤l≤r≤109) — the size of the lost array and the range of numbers in the array.
Output
Print the remainder when dividing by 109+7 the number of ways to restore the array.
Examples
Input
2 1 3
Output
3
Input
3 2 2
Output
1
Input
9 9 99
Output
711426616
Note
In the first example, the possible arrays are : [1,2],[2,1],[3,3].
In the second example, the only possible array is [2,2,2].
思路:首先暴力是不可能的了。
dp[i][j]代表着长度为i,%3为j的组合个数。
我们可以直接求出来[l,r]中对%3之后为0,1,2的数的个数。也就是求出来了dp[1][i]的值。
之后的dp[i][j]可以由dp[i-1][x]和dp[1][y]来得到。其中x和y分别由具体情况而定。
状态转移方程:
for(i=0;i<3;i++) dp[1][i]=(r+3-i)/3-(l+3-i-1)/3;
for(i=2;i<=n;i++)
{
dp[i][0]=(dp[i-1][0]*dp[1][0])%mod+(dp[i-1][1]*dp[1][2])%mod+(dp[i-1][2]*dp[1][1])%mod;
dp[i][1]=(dp[i-1][0]*dp[1][1])%mod+(dp[i-1][2]*dp[1][2])%mod+(dp[i-1][1]*dp[1][0])%mod;
dp[i][2]=(dp[i-1][0]*dp[1][2])%mod+(dp[i-1][1]*dp[1][1])%mod+(dp[i-1][2]*dp[1][0])%mod;
dp[i][0]%=mod;
dp[i][1]%=mod;
dp[i][2]%=mod;
}
完整代码:
#include<bits/stdc++.h>
#define ll long long
#define mod 1000000007
using namespace std;
const int maxx=2e5+100;
ll dp[maxx][3];
int n,l,r;
int main()
{
scanf("%d%d%d",&n,&l,&r);
memset(dp,0,sizeof(dp));
int i;
for(i=0;i<3;i++) dp[1][i]=(r+3-i)/3-(l+3-i-1)/3;
for(i=2;i<=n;i++)
{
dp[i][0]=(dp[i-1][0]*dp[1][0])%mod+(dp[i-1][1]*dp[1][2])%mod+(dp[i-1][2]*dp[1][1])%mod;
dp[i][1]=(dp[i-1][0]*dp[1][1])%mod+(dp[i-1][2]*dp[1][2])%mod+(dp[i-1][1]*dp[1][0])%mod;
dp[i][2]=(dp[i-1][0]*dp[1][2])%mod+(dp[i-1][1]*dp[1][1])%mod+(dp[i-1][2]*dp[1][0])%mod;
dp[i][0]%=mod;
dp[i][1]%=mod;
dp[i][2]%=mod;
}
printf("%lld\n",dp[n][0]);
return 0;
}
可以采用滚动数组的方式进行空间优化:
#include<bits/stdc++.h>
#define ll long long
#define mod 1000000007
using namespace std;
ll x[3],y[3],a[3];
int n,l,r;
int main()
{
scanf("%d%d%d",&n,&l,&r);
memset(x,0,sizeof(x));
memset(y,0,sizeof(y));
for(int i=0;i<3;i++) a[i]=(r+3-i)/3-(l+3-i-1)/3;
y[0]=a[0];
y[1]=a[1];
y[2]=a[2];
for(int i=2;i<=n;i++)
{
x[0]=(y[0]*a[0])%mod+(y[1]*a[2])%mod+(y[2]*a[1])%mod;
x[1]=(y[0]*a[1])%mod+(y[1]*a[0])%mod+(y[2]*a[2])%mod;
x[2]=(y[0]*a[2])%mod+(y[1]*a[1])%mod+(y[2]*a[0])%mod;
x[0]%=mod;
x[1]%=mod;
x[2]%=mod;
y[0]=x[0];y[1]=x[1];y[2]=x[2];
}
cout<<y[0]<<endl;
return 0;
}
努力加油a啊,(o)/~