|
发表于 2019-12-23 11:36:28
|
显示全部楼层
你这样硬算时间复杂度是O[2^n],n大一点会算不过来的。
其实只要考虑一艘船,尽量多装。看剩下的另一艘船是否能装下就行。
正如我前面所说,那么这就化简成对其中一艘船求0-1背包问题了
- def maxCargoLoad(C,W):
- '''
- 贪心算法,在船载重为C,试图装N个货物时,其最大载重为f(N,C),
- 有:f(N)=max(W[N}+f(N-1,C-W[N]),f(N-1,C))
- '''
- ret={};
- def loopfunc(C,i):
- if (i<0):
- return 0
- if (not (C,i) in ret):
- choice=[loopfunc(C,i-1)]
- if (C>=W[i]):
- choice.append(W[i]+loopfunc(C-W[i],i-1))
- ret[(C,i)]=max(choice)
- return ret[(C,i)]
- return loopfunc(C,len(W)-1)
- def CanCarry(C1,C2,W):
- return sum(W)-maxCargoLoad(min(C1,C2),W)<=max(C1,C2)
- C1 = int(input('船1载重为:'))
- C2 = int(input('船2载重为:'))
- W = []
- print("输入集装箱重量,以-1结束")
- while True:
- w0=int(input())
- if (w0<0):
- break
- W.append(w0)
- print("在船的载重为%d %d,集装箱分别重" % (C1,C2),W,"的情况下")
- print("可以装下" if CanCarry(C1,C2,W) else "不可以装下")
-
复制代码
|
|