分而治之
2023-06-13 09:11:57 时间
给定K个整数组成的序列{ N 1 , N2 , …, NK },“连续子列”被定义为{ Ni , Ni+1 , …, Nj },其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。
本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:
数据1:与样例等价,测试基本正确性; 数据2:102个随机整数; 数据3:103个随机整数; 数据4:104个随机整数; 数据5:105个随机整数; 输入格式: 输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。
输出格式: 在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。
输入样例: 6 -2 11 -4 13 -5 -2 输出样例: 20
应该用分而治之思想来解,可以提高算法速度
int Max3( int A, int B, int C )
{ /* 返回3个整数中的最大值 */
return A > B ? A > C ? A : C : B > C ? B : C;
}
int DivideAndConquer( int List[], int left, int right )
{ /* 分治法求List[left]到List[right]的最大子列和 */
int MaxLeftSum, MaxRightSum; /* 存放左右子问题的解 */
int MaxLeftBorderSum, MaxRightBorderSum; /*存放跨分界线的结果*/
int LeftBorderSum, RightBorderSum;
int center, i;
if( left == right ) { /* 递归的终止条件,子列只有1个数字 */
if( List[left] > 0 ) return List[left];
else return 0;
}
/* 下面是"分"的过程 */
center = ( left + right ) / 2; /* 找到中分点 */
/* 递归求得两边子列的最大和 */
MaxLeftSum = DivideAndConquer( List, left, center );
MaxRightSum = DivideAndConquer( List, center+1, right );
/* 下面求跨分界线的最大子列和 */
MaxLeftBorderSum = 0; LeftBorderSum = 0;
for( i=center; i>=left; i-- ) { /* 从中线向左扫描 */
LeftBorderSum += List[i];
if( LeftBorderSum > MaxLeftBorderSum )
MaxLeftBorderSum = LeftBorderSum;
} /* 左边扫描结束 */
MaxRightBorderSum = 0; RightBorderSum = 0;
for( i=center+1; i<=right; i++ ) { /* 从中线向右扫描 */
RightBorderSum += List[i];
if( RightBorderSum > MaxRightBorderSum )
MaxRightBorderSum = RightBorderSum;
} /* 右边扫描结束 */
/* 下面返回"治"的结果 */
return Max3( MaxLeftSum, MaxRightSum, MaxLeftBorderSum + MaxRightBorderSum );
}
int MaxSubseqSum3( int List[], int N )
{ /* 保持与前2种算法相同的函数接口 */
return DivideAndConquer( List, 0, N-1 );
}
浙大mooc课上求最大子列和用的分而治之思想的代码
二分法查找,也称为折半法,是一种在有序数组中查找特定元素的搜索算法。
二分法查找的思路如下:
(1)首先,从数组的中间元素开始搜索,如果该元素正好是目标元素,则搜索过程结束,否则执行下一步。
(2)如果目标元素大于/小于中间元素,则在数组大于/小于中间元素的那一半区域查找,然后重复步骤(1)的操作。
(3)如果某一步数组为空,则表示找不到目标元素。
二分查找法,找数组中的一个数
#include<bits/stdc++.h>
#include<math.h>
using namespace std;
int binaryserch(int a[],int x){
int left=0;
int right=9;
int mid=0;
while(left<=right){
mid=floor((right+left)/2);
if(a[mid]==x)
return mid;
else if(a[mid]<x)
left=mid+1;
else
right=mid+1;
}
return false;
}
int main(){
int a[10]={1,3,5,6,7,9,10,16,18,27};
int b;
cin>>b;
int result=binaryserch(a,b);
cout<<result<<endl;
}
————————————-分治思想先到这。。睡觉