数据结构——分治算法

分治算法的概念

1.将一个规模为n的问题,分解成为k个规模较小的子问题,然后依次递归解决子问题,把求得的解合并就得到然问题的解。
2.应用很多。

实例分析--求最大子数组问题

1.上期没搞懂lua的递归,看了一下决定这期使用lua的递归


求 如何购买股票赚最多的钱。一看知道7到 11天赚最多
1.首先暴力求解的方法
--传入价格表
table={100,113,110,85,105,102,86,63,81,101,94,106,101,79,94,90,97}
table2={} --变化表
for i=2,#table do
local difference=table[i]-table[i-1]
table2[i-1]=difference
end
left,right=0,0
function getprofit() --对table2 操作
local max1,sum=table2[1],0--max1 是一轮的最大值
for j=1,#table2 do
for k=j,#table2 do
sum=sum+table2[k]
if(sum>max1) then
max1=sum
left,right=j,k
end
end
sum=0
end
return left,right
end

a,b=getprofit()
print(a-1,b)
求得 7 11没问题
2. 使用分治法分析问题


--最大子数组的结构体
subarray={startindex,endidex,total}
table={100,113,110,85,105,102,86,63,81,101,94,106,101,79,94,90,97}
df={} --变化表
for i=2,#table do
local difference=table[i]-table[i-1]
df[i-1]=difference
end

local getmax;
getmax=function(low,high,arr) --三个参数

if(low==high) then
subarray.startindex=low
subarray.endidex=high
subarray.total=arr[low]
return subarray
end
local mid=(low+high)/2 //低区间[low,mid] 高区间[mid,high]

local sub1,sub2=subarray,subarray
sub1=getmax(low,mid,arr)
sub2=getmax(mid+1,high,arr)
local total1,startindex1,totaltemp=arr[mid],mid,0
for i=mid,low,-1 do
totaltemp=totaltemp+arr[i]
if(totaltemp>total1) then
total1=totaltemp
startindx1=i
end
end
local total2,endidex1=arr[mid+1],mid+1
for j=mid+1,high,1 do
totaltemp=totaltemp+arr[j]
if(totaltemp>total2) then
total2=totaltemp
endindex1=j
end
end
sub3=subarray
sub3.startindex=startindex1;
sub3.endidex=endindex1
sub3.total=total1+total2
if(sub1.total>=sub2.total and sub1.total>sub3.total)  then
return sub1
elseif(sub2.total>=sub1.total and sub2.total>sub3.total) then
return sub2
else
return sub3
end
end

getmax(1,#df,df)
结果执行不出来就很气。




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值