很难很难的题,高手请帮忙

来源:百度知道 编辑:UC知道 时间:2024/07/02 14:52:34
On a table, there are n apples, the i-th apple has the weight k+i(1 ≤ i ≤ n). Exactly one of the apples is sweet, lighter apples are all bitter, while heavier apples are all sour. The giant wants to know which one is sweet, the only thing he can do is to eat apples. He hates bitter apples and sour apples, what should he do?

For examples, n=4, k=0, the apples are of weight 1, 2, 3, 4. The giant can first eat apple #2.

if #2 is sweet, the answer is #2
if #2 is sour, the answer is #1
if #2 is bitter, the answer might be #3 or #4, then he eats #3, he'll know the answer regardless of the taste of #3

The poor gaint should be prepared to eat some bad apples in order to know which one is sweet. Let's compute the total weight of apples he must eat in all cases.

#1 is sweet: 2
#2 is sweet: 2
#3 is sweet: 2 + 3 = 5
#4 is sweet: 2 + 3 = 5
The total weights = 2 + 2 + 5 + 5 = 14.

This is not optimal. If he e

情况果然很复杂,很多嵌套for循环和if,大概主要想法,你再完善。

函数 ( 传入参数 t, n , k )

{

for ( i=1, i<=n, i++)// 设第i个苹果为甜。
{
for( j=1, j<=n, j++)//设从第j个开始吃
{ 吃之前,把这一次的总吃重设为m==0,所有总吃重设为totalm==0
{ if(j==i)//直接吃到了甜的
m+=j+k;
if (j<i)//吃到了苦的
{ 那就吃下一个
if( j+1==i) //下一个吃到了甜的
m+=j+1+k; //类推 ,不是甜的再吃
...
}
else //吃到了酸的
{那就吃前面一个,类推吃到甜的为止,每吃一个累加吃总重}

totalm+=m //把这次从第j个开始吃的总吃重累加到所有总吃重里
}

//不细写了,记录n个totalm的,比较他们,取最小值,输出

}

//里面肯定有不少错误,只是个大方向,自己研究 ,感觉用递归可能代码简很多,但是太抽象,脑子转不过来。

//不会超时啊,以上只是思想啊,比如吃苹果那里,我是用的if语句,看起来很烦,你改用for,或者do..while什么的判断不就简洁了吗。