第2章 算法分析

2.4.3最大子序列和问题的解

#include<string>
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
//求最大子序列和算法
/* 二分查找法,复杂度nlogn*/
int maxSumRec(const vector<int>&a,int left,int right)
{
	if (left==right)
	{
		if (a[left]>0)
		{
			return a[left];
		}
		else
		{
			return 0;
		}
	}
	int center=(left+right)/2;
	int maxLeftSum=maxSumRec(a,left,center);
	int maxRightSum=maxSumRec(a,center+1,right);

	int maxLeftBorderSum=0,leftBorderSum=0;
	for (int i = center; i < left; i--)
	{
		leftBorderSum+=a[i];
		if (leftBorderSum>maxLeftBorderSum)
		{
			maxLeftBorderSum=leftBorderSum;
		}
	}

	int maxRightBorderSum=0,RightBorderSum=0;
	for (int i = center; i < left; i++)
	{
		RightBorderSum+=a[i];
		if (RightBorderSum>maxRightBorderSum)
		{
			maxRightBorderSum=RightBorderSum;
		}
	}

	return max3(maxLeftSum,maxRightSum,maxRightBorderSum+maxLeftBorderSum);
}
/************************************************************************/
/*线性复杂度算法*/
int maxSubSum4(const vector<int> &a)
{
	int maxSum=0,thisSum=0;
	for (int i = 0; i < a.size(); ++i)
	{
		thisSum+=a[i];
		if (thisSum>maxSum)
		{
			maxSum=thisSum;
		}
		else if(thisSum<0){
			thisSum=0;
		}
	}
}
 
int maxSubSum3(const vector<int> &a)
{
	return maxSumRec(a,0,a.size()-1);
}
int main()
{
 int s;
 cin>> s;
 
 return 0;
}
2.4.4 运行时间中的对数</span>
除分治算法外,对数规律可概括为下列法则:</span>
如果一个算法将常数时间(O(1))将问题的大小削减为其一部分(通常为1/2),那么该算法就算O(logN)的。</span></span>
具有对数特点的几个例子:</span>
 1.二分搜索
定义:给定一个整数X和整数A0,A1,....AN-1,后者已经预先排序并在内存中,求下标i使得Ai=X,如果X不在数据中,则返回-1.</span>
代码:
template<typename Comparable>
int binarySearch(const vector<Comparable> &a,const Comparable) &x)
{
	int low =0,high=a.size()-1;
	while(low<=high)
	{
		int mid=(low+high)/2;
		if(a[mid]<x)
			low=mid+1;
		else if(a[mid]>x) 
			high=mid-1;
		else 
			return mid;
	}
	return NOT_FOUND;
}

 

2.欧几里得算法

  定义:计算最大公因数,通过连续计算余数直到余数是0为止,最后的非零余数就是最大公因数。

 代码:

long gcd(long m,long n)
{
	while(n!=0)
	{
		long rem=m%n;
		m=n;
		n=rem;
	}
	return m;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值