【Uva11762】Race to 1

模拟马尔可夫过程,具体看书。

#include<bits/stdc++.h>
#define N 1000010
using namespace std;
int prime[N],use[N],cnt=0;
void calcprime(){
    cnt=0;memset(use,1,sizeof(use));
    for(int i=2;i<=N;i++){
        if(use[i]){prime[++cnt]=i;}
        for(int j=1;j<=cnt;j++){
            int t=prime[j]*i;if(t>N)break;
            use[t]=0;
            if(i%prime[j]==0)break;
        }
    }
}
bool vis[N];double f[N];
double dfs(int x){
    if(x==1)return 0.0;if(vis[x])return f[x];
    vis[x]=1;double &ans=f[x];
    int g=0,p=0;ans=0;
    for(int j=1;j<=cnt;j++){
        if(prime[j]>x)break;++p;
        if(x%prime[j]==0){g++;ans+=(dfs(x/prime[j]));}
    }
    ans=(ans+p)/g;return ans;
}
inline int read(){
    int f=1,x=0;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(ch<'0'||ch>'9');
    do{x=x*10+ch-'0';ch=getchar();}while(ch>='0'&&ch<='9');
    return f*x;
}
int main(){
    calcprime();int T=read();
    for(int t=1;t<=T;t++){
        printf("Case %d: %.10lf\n",t,dfs(read()));
    }
    return 0;
}#include<bits/stdc++.h>
#define N 1000010
using namespace std;
int prime[N],use[N],cnt=0;
void calcprime(){
    cnt=0;memset(use,1,sizeof(use));
    for(int i=2;i<=N;i++){
        if(use[i]){prime[++cnt]=i;}
        for(int j=1;j<=cnt;j++){
            int t=prime[j]*i;if(t>N)break;
            use[t]=0;
            if(i%prime[j]==0)break;
        }
    }
}
bool vis[N];double f[N];
double dfs(int x){
    if(x==1)return 0.0;if(vis[x])return f[x];
    vis[x]=1;double &ans=f[x];
    int g=0,p=0;ans=0;
    for(int j=1;j<=cnt;j++){
        if(prime[j]>x)break;++p;
        if(x%prime[j]==0){g++;ans+=(dfs(x/prime[j]));}
    }
    ans=(ans+p)/g;return ans;
}
inline int read(){
    int f=1,x=0;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(ch<'0'||ch>'9');
    do{x=x*10+ch-'0';ch=getchar();}while(ch>='0'&&ch<='9');
    return f*x;
}
int main(){
    calcprime();int T=read();
    for(int t=1;t<=T;t++){
        printf("Case %d: %.10lf\n",t,dfs(read()));
    }
    return 0;
}

 

posted @ 2017-05-25 15:55  zcysky  阅读(201)  评论(0编辑  收藏  举报