传送门:http://codeforces.com/contest/1105/problem/C
C. Ayoub and Lost Array
Ayoub had an array aa of integers of size nn and this array had two interesting properties:
- All the integers in the array were between ll and rr (inclusive).
- The sum of all the elements was divisible by 33.
Unfortunately, Ayoub has lost his array, but he remembers the size of the array nn and the numbers ll and rr, 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+7109+7 (i.e. the remainder when dividing by 109+7109+7). In case there are no satisfying arrays (Ayoub has a wrong memory), print 00.
The first and only line contains three integers nn, ll and rr (1≤n≤2⋅105,1≤l≤r≤1091≤n≤2⋅105,1≤l≤r≤109) — the size of the lost array and the range of numbers in the array.
Print the remainder when dividing by 109+7109+7 the number of ways to restore the array.
2 1 3
3
3 2 2
1
9 9 99
711426616
In the first example, the possible arrays are : [1,2],[2,1],[3,3][1,2],[2,1],[3,3].
In the second example, the only possible array is [2,2,2][2,2,2].
题意概括:
要求构造一个长度为 N 的序列,
要求:
1、序列里的数由 【L, R】区间里的数构成。
2、序列里的数值和要能整除 3
解题思路:
一开始还傻傻地以为有什么神奇的规律.....
其实是一道 DP
状态: dp[ i ][ k ] 累积到当前序列第 i 位的数值和 余 k 的方案数
因为要能整除 3 ,所以 k 只能取 0, 1, 2;
sumi 为 区间 【L,R】的模 3 == i 的值的数量
转移方程:
dp[ i ][ 0 ] = dp[i-1][0]*sum0 + dp[i-1][1]*sum2 + dp[i-1][2]*sum1;
dp[ i ][ 1 ] = dp[i-1][0]*sum1 + dp[i-1][1]*sum0 + dp[i-1][2]*sum2;
dp[ i ][ 2 ] = dp[i-1][0]*sum2 + dp[i-1][1]*sum1 + dp[i-1][2]*sum0;
AC code:
1 #include <bits/stdc++.h> 2 #define INF 0x3f3f3f3f 3 #define LL long long 4 using namespace std; 5 const LL MOD = 1e9+7; 6 const int MAXN = 2e5+10; 7 LL ans; 8 LL dp[MAXN][4]; 9 10 int main() 11 { 12 LL N, L, R; 13 LL it0 = 0, it1 = 0, it2 = 0; 14 scanf("%I64d %I64d %I64d", &N, &L, &R); 15 LL len = R-L+1; 16 LL c = len/3LL, d =len%3LL; 17 it0 = c; it1 = c; it2 = c; 18 if(d){ 19 LL t = d==2?1:0; 20 if(L%3==0) it0++, it1+=t; 21 else if(L%3 == 1) it1++, it2+=t; 22 else it2++,it0+=t; 23 } 24 25 dp[1][0] = it0; 26 dp[1][1] = it1; 27 dp[1][2] = it2; 28 29 for(int i = 2; i <= N; i++){ 30 dp[i][0] = ((dp[i-1][0]*it0)%MOD + (dp[i-1][1]*it2)%MOD + (dp[i-1][2]*it1)%MOD)%MOD; 31 32 dp[i][1] = ((dp[i-1][1]*it0)%MOD + (dp[i-1][0]*it1)%MOD + (dp[i-1][2]*it2)%MOD)%MOD; 33 34 dp[i][2] = ((dp[i-1][2]*it0)%MOD + (dp[i-1][1]*it1)%MOD + (dp[i-1][0]*it2)%MOD)%MOD; 35 36 } 37 38 printf("%I64d ", dp[N][0]%MOD); 39 return 0; 40 41 }