笛卡尔树

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <set>
#include <stack>

using namespace std;
typedef long long ll;
const int mod = 1e9+7;
const int maxn = 1e6+10;

struct node {
       int val,l,r;
}nodes[maxn];

int a[maxn],t,n,num[maxn],st[maxn];

ll mypow(ll x, int y) {
    ll ans = 1;
    while (y) {
        if (y & 1) ans = ans * x % mod;
        x = x * x % mod;
        y >>= 1;
    }
    return ans;
}

int build() {
    int pre = 0,top = 0,sz = 0, root = 0;
    for (int i = 1; i <= n; i++) {
        while(top > 0 && nodes[st[top]].val < a[i]) pre = st[top--];
        nodes[++sz].val = a[i];
        if (top == 0) root = sz;
        else nodes[st[top]].r = sz;
        nodes[sz].l = pre;
        st[++top] = sz;
        pre = 0;
    }
    return root;
}

void trans(int u) {
     if (u == 0) return;
     trans(nodes[u].l);
     trans(nodes[u].r);
     num[u] = num[nodes[u].l]+num[nodes[u].r]+1;
}

int main() {
    scanf ("%d",&t);
    while(t--) {
        scanf ("%d",&n);
        for (int i = 1; i <= n; i++) scanf ("%d",&a[i]);
        for (int i = 1; i <= n; i++) nodes[i].l = nodes[i].r = nodes[i].val = 0,num[i] = 0;
        trans(build());
        ll ans = (ll) n*mypow(2,mod-2)%mod;
        for (int i = 1; i <= n; i++) ans = ans*mypow(num[i],mod-2)%mod;
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/kwahia/article/details/81225932