题目:有n个小球,其中有一个比其他的都要重,已知有一个天平,怎么用最少的次数把小球找出来?
个人代码如下:
#include <iostream>
#include <numeric>
using namespace std;
int GetAbnormalBall(int a[], int begin, int end, int &count)
{
if(begin == end)
return a[begin];
int Num = (end - begin) + 1;
int HalfNum = Num / 2;
++count;
int fweight = accumulate(a + begin, a + begin + HalfNum, 0);
int bweight = accumulate(a + begin + HalfNum, a + begin + 2 * HalfNum, 0);
if(Num % 2 != 0) //剩余数量是奇数的时候
{
if(fweight == bweight)
return a[end];
else if(fweight > bweight)
return GetAbnormalBall(a, begin, begin + HalfNum - 1, count);
else
return GetAbnormalBall(a, begin + HalfNum, end, count);
}
else if(fweight > bweight) //剩余数量是偶数的时候
return GetAbnormalBall(a, begin, begin + HalfNum - 1, count);
else if(fweight <