测试案例:
思路很简单,都在代码的注释里,有什么问题可以随时问,望采纳!
int main()
{
while (1) {
int n;//n为蜡烛长度
double time = 0; //time为花费时间
printf("请输入蜡烛长度:");
scanf_s("%d", &n);
int longPart = 0, shortPart = 0;//定义蜡烛的长短
while (n >= 2) {
//随机产生切断蜡烛的位置
int randNum = (rand() % (n - 1)) + 1;
//获取两段蜡烛的长短
longPart = randNum * 2 >= n ? randNum : n - randNum;
shortPart = n - longPart;
//获取同时燃烧所花费时间
time += shortPart;
//剩余蜡烛的长度
n = longPart - shortPart;
}
//只剩下最后不可分的蜡烛的燃烧事件
time += n;
printf("花费时间为:%d\n", time);
}
}
第一次切分后,第二次期望直接算,这样可以吗
不好意思,昨天没有正确理解题意。今天重新写了一下,不知道对数学上“求期望”的理解对不对
#include <iostream>
#include <algorithm/minmax.hpp>
using namespace boost;
int main()
{
int n(0); //蜡烛长度
float time_expect(0); //期望时长
printf("请输入蜡烛长度:");
scanf_s("%d", &n);
int longPart = 0, shortPart = 0;//两段蜡烛的长短
float time_fact(0); //实际总时长
for (int pos1 = 1; pos1 < n; pos1++) {
//第一次分割
auto pair = minmax(pos1, n- pos1);
longPart = get<1>(pair);//
shortPart = n - longPart;
//第一次燃烧时长为:最短蜡烛燃烧时长
int time1 = shortPart;
//剩余长度last
int last = longPart - shortPart;
//第二次分割
float time2_expect(0); //第二次期望燃烧时长
if (last >= 2) {
int time2_all(0); //第二次燃烧
for (int pos2 = 1; pos2 < last; pos2++) {
auto pair2 = minmax(pos2, last - pos2);
//第二次燃烧时长为:最长蜡烛燃烧时长
time2_all += get<1>(pair2);
}
time2_expect = (float)time2_all / (float)(last - 1);
}
else {
time2_expect = (float)last;
}
time_fact += ((float)time1 + time2_expect);
}
time_expect = time_fact / (float)(n - 1);
printf("花费时间为:%.4lf\n", time_expect);
}