LightOJ 1038 Race to 1 Again(概率期望DP)

这里写图片描述

题意

    给出一个数字n,我们可以选择1~n中可以被n整除的数字,然后用n出得到一个新的数字 n1 ;然后再找所有 n1 的因子,用 n1 除,直到得到1;问除的次数的期望值。

思路

    对于一个数n,我们设dp[i]为i变到1的期望,我们可以根据期望从后往前推,则dp[i]=(dp[1]+dp[ c1 ]+…+dp[i]+num)/num。对于这个值我们进行扫一遍找因子然后dfs下去就行了,记得要记忆化,还有,对于1和n要特殊处理。

Code

#pragma GCC optimize(3)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
inline void readInt(int &x) {
    x=0;int f=1;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
    while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
    x*=f;
}
inline void readLong(ll &x) {
    x=0;int f=1;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
    while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
    x*=f;
}
/*================Header Template==============*/
int T,n;
double f[100010];
inline double dfs(int x) {
    if(f[x]!=-1.0)
        return f[x];
    double ans=0,cnt=2;
    for(int i=2;i*i<=x;i++) {
        if(x%i==0) {
            cnt++;
            ans+=dfs(x/i);
            if(i*i!=x) {
                ans+=dfs(i);
                cnt++;
            }
        }
    }
    ans+=cnt;
    ans/=(cnt-1);
    return f[x]=ans;
}
int main() {
    readInt(T);
    for(int ca=1;ca<=T;ca++) {
        readInt(n);
        for(int i=1;i<=n;i++)
            f[i]=-1;
        f[1]=0;
        printf("Case %d: %.6lf\n",ca,dfs(n));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值