分治法解决最大子段和问题
int MaxSum(int a[ ], int left, int right)
{
int sum=0,midsum=0,leftsum=0,rightsum=0;
int center,s1,s2,lefts,rights;
if (left==right) { //如果序列长度为1,直接求解
sum=a[left];
}
else {
center=(left+right)/2; //划分
leftsum=MaxSum(a, left, center);
//对应情况①,递归求解
rightsum=MaxSum(a, center+1, right); //对应情况②,递归求解
s1=0; lefts=0; //以下对应情况③,先求解s1
for (int i=center; i>=left; i--)
{
lefts+=a[i];
if (lefts>s1) s1=lefts;
}
s2=0; rights=0; //再求解s2
for (int j=center+1; j<=right; j++)
{
rights+=a[j];
if (rights>s2) s2=rights;
}
sum=s1+s2; //计算情况③的最大子段和
if (sum
减治法解决淘汰赛冠军问题
bool Comp(char A,char B){//A大就赢
if(A1) {
i=i/2;
for (j=0; j
减治法和递归解决假币问题
假设:假币比较轻
int a[]={2,2,2,2,2,1,2,2};
int Coin(int low,int high,int n){
int i,num1,num2,num3;
int add1=0,add2=0;
if(n==1) return low+1;//返回序号,故下标加一
if(n%3==0) num1=num2=n/3;
else num1=num2=n/3+1;
num3=n-num1-num2;
for(i=0;iadd2) return Coin(low+num1,low+num1+num2-1,num2);
else return Coin(low+num1+num2,high,num3);
}
测试:
int main(){
int a[]={-20,11,-4,13,-5,-2};
cout<