#include<iostream>
#include<ctime>
using namespace std;
int Max_3(int a, int b, int c) //3个数中大
{
if (a > b)
{
if (a > c)
return a;
else
return c;
}
else
{
if (b > c)
return b;
else
return c;
}
}
int MaxSum_1(const int a[], int n) //穷举法
{
int maxsum=0, thissum,j,k;
for (int i = 0; i < n; i++)
for (j = i; j < n; j++)
{
thissum = 0;
for (k = i; k <= j; k++)
thissum += a[k];
if (thissum > maxsum)
maxsum = thissum;
}
return maxsum;
}
int MaxSum_2(const int a[], int n) //穷举法改进
{
int maxsum = 0, thissum, j;
for (int i = 0; i < n; i++)
{
thissum = 0;
for (j = i; j < n; j++)
{
thissum += a[j];
if (thissum > maxsum)
maxsum = thissum;
}
}
return maxsum;
}
int MaxSum_3(const int a[], int n) //联机算法
{
int maxsum = 0, thissum = 0,i;
for (int i = 0; i < n; i++)
{ thissum += a[i];
if (thissum > maxsum)
maxsum = thissum;
else if (thissum < 0)
thissum = 0;
}
return maxsum;
}
int MaxSum_4(int a[],int left,int right) // 分治算法,递归
{
int leftmax, rightmax; //左边和右边的最大数
int leftbordermax, rightbordermax; //左右边界的最大数
int leftborde, rightborde; //边界左右的值
int center,i;
if (left == right) //基准情形
if(a[left]>0)
return a[left];
else
return 0;
center = (left + right) / 2;
leftmax = MaxSum_4(a, left, center);
rightmax = MaxSum_4(a, center+1, right);
leftbordermax = leftborde = 0; //左边界的最大值
for (i = center; i >= left; i--)
{
leftborde += a[i];
if (leftborde > leftbordermax)
leftbordermax = leftborde;
}
rightbordermax = rightborde = 0; //右边界的最大值
for (i = center+1; i <= right; i++)
{
rightborde += a[i];
if (rightborde > rightbordermax)
rightbordermax = rightborde;
}
return Max_3(leftmax, leftbordermax + rightbordermax, rightmax);
}
int main()
{
int max_sum, s[10000];
for (int i = 0; i < 10000; i += 3)
{
s[i] = 1;
s[i + 1] = -1;
s[i + 2] = 6;
}
clock_t t_0, t;
t_0 = clock();
max_sum = MaxSum_1(s, 1000);
t = clock()-t_0;
cout << "1:" << endl;
cout << "时间:" << t << "毫秒" << endl;
cout << "maxsum_1 = " << max_sum << endl;
t_0 = clock();
max_sum = MaxSum_2(s, 1000);
t = clock() - t_0;
cout << "2:" << endl;
cout << "时间:" << t << "毫秒" << endl;
cout << "maxsum_2 = " << max_sum << endl;
t_0 = clock();
max_sum = MaxSum_3(s, 1000);
t = clock() - t_0;
cout << "3:" << endl;
cout << "时间:" << t << "毫秒" << endl;
cout << "maxsum_3 = " << max_sum << endl;
t_0 = clock();
max_sum = MaxSum_4(s,0,999);
t = clock() - t_0;
cout << "4:" << endl;
cout << "时间:" << t << "毫秒" << endl;
cout << "maxsum_4 = " << max_sum << endl;
cin.get();
return 0;
}
【算法】最大子序列的四种算法
最新推荐文章于 2022-03-17 17:04:37 发布