ZOj 3929Deque and Balls

来源:互联网 发布:学编程有什么好书 编辑:程序博客网 时间:2024/05/18 19:42

There are n balls, where the i-th ball is labeled as pi. You are going to put n balls into a deque. In the i-th turn, you need to put the i-th ball to the deque. Each ball will be put to both ends of the deque with equal probability.

Let the sequence (x1x2, ..., xn) be the labels of the balls in the deque from left to right. The beauty of the deque B(x1x2, ..., xn) is defined as the number of descents in the sequence. For the sequence (x1x2, ..., xn), a descent is a position i (1 ≤ i < n) with xi > xi+1.

You need to find the expected value of B(x1x2, ..., xn).

Deque is a double-ended queue for which elements can be added to or removed from either the front (head) or the back (tail).

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

The first line contains an integer n (2 ≤ n ≤ 100000) -- the number of balls. The second line contains n integers: p1p2, ..., pn (1 ≤ pi ≤ n).

Output

For each test case, if the expected value is E, you should output E⋅2n mod (109 + 7).

Sample Input

221 232 2 2

Sample Output

20
计算期望乘上2^n,其实就相当于求所有可能的下降次数总和。
一个一个往队列里加数,只要考虑之前不等于该数的数出现在队首和队尾的全部可能即可。
#include<map>#include<set>#include<cmath>#include<queue>#include<stack>#include<bitset>#include<cstdio>#include<string>#include<cstring>#include<algorithm>#include<functional>using namespace std;typedef long long LL;const int low(int x) { return x&-x; }const int INF = 0x7FFFFFFF;const int mod = 1e9 + 7;const int maxn = 1e5 + 10;int T, n, m, a[maxn], f[maxn], c[maxn];int main() {scanf("%d", &T);while (T--){scanf("%d", &n);c[0] = 1;for (int i = 1; i <= n; i++){scanf("%d", &a[i]); f[i] = 0;c[i] = (c[i - 1] << 1) % mod;}LL ans = 0, sum = 0;for (int i = 1; i <= n; i++){(ans += (LL)c[n - i] * (sum - f[a[i]] + mod)) %= mod;(f[a[i]] += c[max(1, i - 1)]) %= mod;(sum += c[max(1, i - 1)]) %= mod;}printf("%lld\n", ans);}return 0;}



0 0
原创粉丝点击