## 找质量不同铁块问题(分治法)

### C++ 代码描述

#include<iostream>

using namespace std;

int checkFalseCoin(int begin,int end,int coins[]){
if((end-begin)==1){
return (coins[end]>coins[begin])?end:begin;
}
if((( end - begin + 1 ) & 1) == 0 ){
// 元素个数是双数
int leftSum = 0,rightSum = 0;
int middle = (end + begin + 1) / 2;
for(int i = begin ; i < middle ; i ++ ){
leftSum += coins[i];
}
for(int i = middle ; i <= end ; i ++ ){
rightSum += coins[i];
}
if( leftSum < rightSum){
return checkFalseCoin(middle,end,coins);
}else if(leftSum > rightSum){
return checkFalseCoin(begin,middle-1,coins);
}else{
return end;
}
}else{
// 元素个数是单数
int leftSum = 0,rightSum = 0;
int middle = (end + begin) / 2;
for(int i = begin ; i < middle ; i ++ ){
leftSum += coins[i];
}
for(int i = middle + 1 ; i <= end ; i ++ ){
rightSum += coins[i];
}
if( leftSum < rightSum){
return checkFalseCoin(middle,end,coins);
}else if(leftSum > rightSum){
return checkFalseCoin(begin,middle,coins);
}else{
return middle;
}
}
}

int main(){
int data[] = {1,1,1,1,1,2,1,1,1,1,1,1,1,1};
int n = 14;
std::cout << checkFalseCoin(0,n-1,data) << endl;
return 0;
}