Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 131 Accepted Submission(s): 41
Problem Description
There is a positive integer sequence a1,a2,…,an with some unknown positions, denoted by 0. >Little Q will replace each 0 by a random integer within the range [1,m] equiprobably. After that, he >will calculate the value of this sequence using the following formula :
Little Q is wondering what is the expected value of this sequence. Please write a program to >calculate the expected value.
Input
The first line of the input contains an integer T(1≤T≤10), denoting the number of test cases.
in each test case, there are 2 integers n,m(4≤n≤100,1≤m≤100) in the first line, denoting the length >of the sequence and the bound of each number.
In the second line, there are n integers a1,a2,…,an(0≤ai≤m), denoting the sequence.
In the third line, there are m integers v1,v2,…vm(1≤vi≤109), denoting the array v.
Output
For each test case, print a single line containing an integer, denoting the expected value. If the answer is A / B, please print C(0≤C<109+7) where A≡C×B(mod109+7).
Sample Input
2
6 8
4 8 8 4 6 5
10 20 30 40 50 60 70 80
4 3
0 0 0 0
3 2 4
Sample Output
8000
3
Source
2018 Multi-University Training Contest 3
题意:
给定一个数列,数列中为0的点表示这个地方可以取1 ~ m的任意一个数,给定上面所描述的累成的定义,求答案的期望值。
思路:
官方题解:
设 f(i,x,y,z)表示考虑前 i 个位置,
a(i) = x, gcd(a(i) , a(i-1) ) = y, gcd(a(i) , a(i−1) , a(i−2) ) = z 的期望。
枚举 a i+1 的值转移即可。
时间复杂度 O(nmS),其中 S 表示 (x, y, z) 的状态数。
显然合法状态中 y|x, z|y,当 m = 100 时 S = 1471。
根据官方的题解,明显我们开不下100 * 100 * 100 * 100 的数组,我们可以考虑滚动数组,因为f(i,x,y,z) 只与f(i-1, , , ,)的值有关,那么我们就可以开一个 2 * 100 * 100 * 100的数组。
那么我们应该怎么样枚举,如果我们暴力枚举的话,那么时间复杂度是n*(m ^ 4)。考虑优化,这题的关键是求gcd,那么我们可以枚举因子,一个数的因子个数不会有太多,再加上我们要枚举因子的因子,所以最坏情况下大概是1500的复杂度,完全可以接受。具体的细节实现可以看代码。
代码:
1 | /************************************************************************* |