Interesting Permutation(思维)

题目描述
DreamGrid has an interesting permutation of 1, 2,…, n denoted by a1, a2,…, an. He generates three sequences f, g and h, all of length n, according to the permutation a in the way described below:
• For each 1 ≤ i ≤ n, fi = max { a1, a2,…, ai } ;
• For each 1 ≤ i ≤ n, gi = min { a1, a2,…, ai } ;
• For each 1 ≤ i ≤ n, hi = fi − gi.
BaoBao has just found the sequence h DreamGrid generates and decides to restore the original
permutation. Given the sequence h, please help BaoBao calculate the number of different permutations
that can generate the sequence h. As the answer may be quite large, print the answer modulo 109 + 7.

输入
The input contains multiple cases. The first line of the input contains a single integer T (1 ≤ T ≤ 20 000),the number of cases.
For each case, the first line of the input contains a single integer n (1 ≤ n ≤ 105), the length of the permutation as well as the sequences. The second line contains n integers h1, h2,…, hn(1 ≤ i ≤ n, 0 ≤ hi ≤ 109).
It’s guaranteed that the sum of n over all cases does not exceed 2 · 106.

输出
For each case, print a single line containing a single integer, the number of different permutations that can generate the given sequence h. Don’t forget to print the answer modulo 109+ 7.

样例输入
3
3
0 2 2
3
0 1 2
3
0 2 3

样例输出
2
4
0

提示
For the first sample case, permutations { 1, 3, 2 } and { 3, 1, 2 } can both generate the given sequence.
For the second sample case, permutations { 1, 2, 3 } , { 2, 1, 3 } , { 2, 3, 1 } and { 3, 2, 1 } can generate the given sequence.

思路
对于一个h序列,当h1==0 或 hii-1 或 hi>=n 时,该序列不成立,即输出0,当存在序列时, 当 hi>hi-1时,ans*=可插空位,可插空位-1,当 hi==hi-1时,该位为前n项的最小值或最大值,ans*=2,可插空位+(hi-hi-1-1)

代码实现

#pragma GCC optimize(3,"Ofast","inline")
#include

using namespace std;
typedef long long ll;
const int N=1e5+5;
const int M=10005;
const int INF=0x3f3f3f3f;
const ll mod=1e9+7;
typedef pair<int,int>P;

int T;
int n;
ll h[N];

int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        bool flag=false;
        for(int i=1;i<=n;i++)
        {
            scanf("%lld",&h[i]);
            if(h[i]>=n || h[i]<h[i-1]) flag=true;
        }
        if(h[1]!=0) flag=true;
        if(flag)
        {
            puts("0");
            continue;
        }
        ll cnt=0;
        ll ans=1;
        for(int i=2;i<=n;i++)
        {
            if(h[i]>h[i-1])
            {
                ans*=2;
                ans%=mod;
                cnt+=(h[i]-h[i-1]-1);
            }
            else
            {
                ans*=cnt;
                ans%=mod;
                cnt--;
            }
        }
        printf("%lld\n",ans%mod);
    }
    return 0;
}

你可能感兴趣的:(思维)