hdu 5145 NPY and girls (莫队算法)

            题意:有一个长度为n的数字序列,m次询问一个区间l-r中数字重新排列的方案数(mod 10^9+7)。

            明显的莫队算法,只需要排序,然后预处理一下逆元就可以了。

            所谓的莫队算法,最初版本是求曼哈顿距离最小生成树的。但是现在一般是分块排序,这样就可以做到n*sqrt(n)的复杂度,对于这个可以大概yy一下。如果对于每个区间可以O(1)的扩展区间的话,那么莫队算法就可以派上用场了。。


#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;

const int maxn = 30300;

const int MOD = 1000000007;

int MID;

int a[maxn], p[maxn];
int cnt[maxn];

struct query
{
    int l, r, id;
    bool operator < (const query& rhs) const
    {
        return l / MID < rhs.l / MID || (l / MID == rhs.l / MID && r < rhs.r);
    }
}q[maxn];

long long Inv(long long x, long long mod)///mod为质数
{
    long long r, y;
    for(r = 1, y = mod - 2; y; x = x * x % mod, y >>= 1)
        (y & 1) && (r = r * x % mod);
    return r;
}

int inv[maxn];

void init()
{
    inv[0] = 1;
    for(int i = 1; i < maxn; i ++)
    {
        inv[i] = Inv(i, MOD);
    }
}

int main()
{
    int T, n, m;
    init();
    scanf("%d", &T);
    while(T --)
    {
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i ++)
            scanf("%d", &a[i]);
        a[0] = 0;
        for(int i = 0; i < m; i ++)
        {
            scanf("%d%d", &q[i].l, &q[i].r);
            q[i].id = i;
        }
        MID = sqrt(n + 0.0);
        sort(q, q + m);
        int L = 1, R = 1;
        int ans = 1, tot = 1;
        memset(cnt, 0, sizeof(cnt));
        cnt[a[1]] ++;
        for(int i = 0; i < m; i ++)
        {
            while(R < q[i].r)
            {
                R ++; tot ++; cnt[a[R]] ++;
                ans = 1ll * ans * inv[cnt[a[R]]] % MOD;
                ans = 1ll * ans * tot % MOD;
            }
            while(R > q[i].r)
            {
                ans = 1ll * ans * cnt[a[R]] % MOD;
                ans = 1ll * ans * inv[tot] % MOD;
                R --; tot --; cnt[a[R + 1]] --;
            }
            while(L < q[i].l)
            {
                ans = 1ll * ans * cnt[a[L]] % MOD;
                ans = 1ll * ans * inv[tot] % MOD;
                L ++; tot --; cnt[a[L - 1]] --;
            }
            while(L > q[i].l)
            {
                L --; tot ++; cnt[a[L]] ++;
                ans = 1ll * ans * inv[cnt[a[L]]] % MOD;
                ans = 1ll * ans * tot % MOD;
            }
            p[q[i].id] = ans;
        }
        for(int i = 0; i < m; i ++)
        {
            printf("%d\n", p[i]);
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值