原题目:
Rimi learned a new thing about integers, which is - any positive integer greater than 1 can be divided by its divisors. So, he is now playing with this property. He selects a number N. And he calls this D.
In each turn he randomly chooses a divisor of D (1 to D). Then he divides D by the number to obtain new D. He repeats this procedure until D becomes 1. What is the expected number of moves required for N to become 1.
Input
Input starts with an integer T (≤ 10000), denoting the number of test cases.
Each case begins with an integer N (1 ≤ N ≤ 105).
Output
For each case of input you have to print the case number and the expected value. Errors less than 10-6 will be ignored.
Sample Input
3
1
2
50
Sample Output
Case 1: 0
Case 2: 2.00
Case 3: 3.0333333333
中文概要:
给出一个数D,每次可以选择数D的一个因子,用数D除上这个因子得到一个新的数D,为数D变为1的操作次数的期望为多少?
#include <cstdio>
#include <cstring>
#include <algorithm>
#include<math.h>
using namespace std;
const int maxn = 100010;
const int INF = 0x3f3f3f3f;
double dp[maxn];
int main()
{
int t;
scanf("%d",&t);
memset(dp,0,sizeof(dp));
for(int i=2;i<maxn;i++)
{
double num,ans;
num=-1;
ans=0;
int nu=(int)sqrt(i);
for(int j=1;j<=nu;j++)
{
if(i%j==0)
{
num++;
ans+=1+dp[j];//ans表示期望和
if(j!=i/j)//在左在右各一个因子
{
num++;
ans+=1+dp[i/j];
}
}
dp[i]=ans/num;
}
}
for (int i=1; i<=t; i++)
{
int n;
scanf ("%d", &n);
printf ("Case %d: %lf\n", i, dp[n]);
}
return 0;
}
思路:
不看解析根本想不出来系列
看了解析秒懂系列
这道题目可以这样理解,假设n的因子个数是num个,每一个因子分别为a[1], a[2], a[3], ….a[num],
然后 dp[n] (从n到1次数的期望) = (dp[a[1]]+1)(因为n/a[1]不为1,所以步数+1) * 1/num +(dp[a[2]] + 1) * 1/num +……+(dp[a[num]]+1) * 1/num.
也就是:
dp[n] = (dp[a[1]] + dp[a[2]] + dp[a[3]] + …… +dp[a[num]] + num)/num;
因为因子数包含本身,所以
a[num] = n;
dp[a[num]] = dp[n]
所以,上面的式子化简为:
dp[n] = (dp[a[1]] + dp[a[2]] + dp[a[3]] + …… +dp[n] + num)/num;
移项得:
(num-1)/num * dp[n] = (dp[a[1]] + dp[a[2]] + dp[a[3]] + …… +num)/num;
等价于:
dp[n] = (dp[a[1]] + dp[a[2]] + dp[a[3]] + …… +num)/(num-1);
对应代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <set>
#include <cstring>
#include <cstdlib>
#include <vector>
using namespace std;
double dp[123123];
int main()
{
dp[1] = 0;
for(int i=2; i<=100000; i++)
{
dp[i] = 0;
int num = 0;
for(int j=1; j*j<=i; j++)//找一半就可以了
{
if(i%j==0)
{
dp[i] += dp[j];
num++;
if(i/j!=j)//在左右各一个
{
num++;
dp[i] += dp[i/j];
}
}
}
dp[i] = (dp[i]+num)/(num-1);//上面的公式
}
int t;
scanf("%d", &t);
for(int T=1; T<=t; T++)
{
int n;
scanf("%d", &n);
printf("Case %d: %lf\n", T, dp[n]);
}
return 0;
}
两个代码除了计算公式不太同其他无本质区别