ZOj 3929 Deque and Balls

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
2
2
1 2
3
2 2 2
Sample Output
2
0
计算期望乘上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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值