ZOJ 3929

Deque and Balls
Time Limit: 2 Seconds       Memory Limit: 65536 KB

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 (x1, x2, ..., xn) be the labels of the balls in the deque from left to right. The beauty of the deque B(x1, x2, ..., xn) is defined as the number of descents in the sequence. For the sequence (x1, x2, ..., xn), a descent is a position i (1 ≤ i < n) with xi > xi+1.

You need to find the expected value of B(x1, x2, ..., 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: p1, p2, ..., 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


 

题意:t组测试数据,每个测试数据包含n个球,第i个球的值为ai, 现在有一个队列,可以插在队首或者队尾,从第一个球开始插入,直到n个球全部插完。设每次往队首或队尾插的概率相等,定义队列的值为a(i)>a(i+1)的个数,求球队列值的数学期望。答案乘上2的n次方mod 10e9+7。


#include<iostream>
#include<string.h>  
#define ll long long  
#define mod 1000000007  
using namespace std;  
ll power[100005];  //此数组代表2的n次方%mod
ll r[100005];  //此数组代表一端放数字为当前数字的方案数有ri个
ll dp[100005];  //代表前n个数能组成的序列的总的值
int main(){  
    power[0]=1;  
    for(int i=1;i<=100000;++i){  
        power[i]=(power[i-1]*2)%mod;  
    }  
    int t;  
    cin>>t;  
    while(t--){  
        memset(r,0,sizeof(r));  
        memset(dp,0,sizeof(dp));  
        int n,a;  
        cin>>n;  
        for(int i=1;i<=n;++i){  
            cin>>a;  
            dp[i]=(dp[i-1]*2+power[i-2]-r[a]+mod)%mod;  //此数可以往队首或者队尾插入,扩展出来的就是dp[i-1]*2,power[i-2]代表没放此数时总的排列的可能数,r[a]代表与当前数放的相邻的方案数,(ps:对于任意一个不等与a的数,都有机会放到队首或者队尾,所以当第i个数插入时,值就会加1,因为要么大于,要么小于,当相等时就不行)。          
             if(i==1)  
                r[a]=(r[a]+1)%mod;  //i==1,放左边或者右边都一样
             else  
                r[a]=(r[a]+power[i-2])%mod;  //否则有2的n-2次方种可能
        }  
        cout<<dp[n]*2%mod<<endl; //数学期望是除以总共可能的序列数,也就是2的n-1次方,再乘上2的n次方也就是乘以2了
    }  
    return 0;  
}  



你可能感兴趣的:(ZOJ 3929)