牛客网暑期ACM多校训练营(第五场)F.take 思维+树状数组

题目链接:https://www.nowcoder.com/acm/contest/143/F

题目大意:

有 n 个箱子,第 i 个箱子有 p[i] 的概率出现大小为 d[i] 的钻石

现在 小A 一开始手里有一个大小为 0 的钻石,他会根据 i 从小到大打开箱子,

如果箱子里有钻石且比小 A 手中的大,那么小 A 就会交换手中的钻石和箱子里的钻石

求期望的交换次数

1<=n<=10^5

题目思路:

实际上,如果我们规定某一颗钻石K是最后的手持的话,那么比它大的钻石盒子就不能开出钻石,

那么显然钻石K对答案的贡献就是打开K的盒子有钻石的概率和打开比他大的盒子但是没钻石的概率

这样以来实际上顺序开对这种计算方式是没影响的。

这样的话我们对钻石大小从大到小排序,枚举每一颗钻石得到贡献,其和就是答案。

这里可以用树状数组维护前缀积能快速得到比当前钻石大的钻石开不出来的概率乘积。

时间复杂度O(nlogn)

另外有一点要注意的是,因为题目给出的概率是p*100,并且最终结果要取模,因此推荐p用整型保存,计算概率的时候用p*(100的逆元)。

还有就是因为树状数组维护的是前缀积,因此初始化都要变为1.

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<vector>
#define INF 1e9
using namespace std;
typedef long long ll;
const int maxn=100000+100;
const int mod=998244353;
struct nodes
{
    ll p,d;
    int id;
    bool operator <(const nodes&a)const
    {
        if(d==a.d)return id<a.id;
        return d>a.d;
    }
}num[maxn];
ll tc[maxn];
int lowbit(int x)
{
    return x&(-x);
}

void add(int x ,ll d)
{
    while(x<maxn)
    {
        tc[x]=(tc[x]*d)%mod;
        x+=lowbit(x);
    }
}
ll query(int x)
{
    ll sum=1;
    while(x>0)
    {
        sum=(sum*tc[x])%mod;
        x-=lowbit(x);
    }
    return sum;
}
ll pow_m(ll a,ll m,ll mod)
{
    ll ans=1;
    while(m)
    {
        if(m&1)ans*=a;
        ans%=mod;
        a*=a;
        a%=mod;
        m>>=1;
    }
    return ans;
}
ll getinv(ll a,ll mod)
{
    return pow_m(a,mod-2,mod);
}
int main()
{
    ll inv =getinv(100,mod);
    int n;
    scanf("%d",&n);
    for(int i=0;i<maxn-10;i++)tc[i]=1;
    for(int i=0;i<n;i++)
    {
        scanf("%d%d",&num[i].p,&num[i].d);
        num[i].id=i+1;
    }
    sort(num,num+n);
    ll ans=0;
    for(int i=0;i<n;i++)
    {
        ll tmp=num[i].p*inv%mod*query(num[i].id-1)%mod;
        ans=(ans+tmp)%mod;
        add(num[i].id,(100-num[i].p)*inv%mod);
    }
    printf("%lld\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36782366/article/details/81566925