[英]How do I change this greedy algorithm to predict the with the most overall score?
大家好,這是我在這里的第一篇文章。
所以今天在我大學class期間,我們的教授給了我們一個任務,寫一個算法:
編寫一個 function 以返回在棋盤游戲中獲得最高分所需的步數:
這是一種貪心算法:
在我想象了這個例子之后,我意識到我的方法是錯誤的:
所以想象一個數組 {1, -40, -40, -40, -40, -1, -38, -40, -40, -40, -40, -40, 1}
我的貪心算法從 1 開始,看到四個 -40、一個 -38 和一個 -1。 它選擇 -1 是因為它是最好的選擇,但現在我們將得到以下結果:1 + (-1) + (-38) + 1 = -37,但是如果我們選擇 -38 而不是 -1,我們最終會得到:1 + (-38) + 1 = -36。
這只是問題可能的一個簡單示例,我想我必須檢查每條可能的路徑,因為貪婪算法不會檢查那里的最佳路徑,只檢查最適合某個特定時刻的路徑。
我想知道在這里是否可以選擇具有所有可能性的圖,但是如果我們只有一個負數數組,那么我們最終會得到一個最大大小約為(99999^6?)的圖,這將導致占用過多的memory。
我是一個新手,我的想法已經用完了。 誰能指出我正確的方向?
等一下。 在這里使用最大堆可能會出現貪婪。
Push A[0..max(5, size_of_input_array - 1)] values in the max heap in the form (value, index in the array)
max_score = 0
For i = 6 to size_of_input_array - 1:
while(max heap is not empty and (top of the max heap).index < curr_index):
pop the max heap
if(max heap is not empty):
max_score += (top of the max heap).value
curr_index = (top of the max heap).index
pop the max heap
push the (input_array[i], i) into the max heap
return max_score == INT_MIN? (is max heap empty? 0: (top of the max heap).value): max_score
不提供完整的工作代碼,因為這是您的任務。 上面缺少的任何東西都是微不足道的。
您也可以嘗試使用深度優先搜索、動態編程。 但上述貪心解決方案是有效的。
時間復雜度:O(N*log(6)) => O(N)
空間復雜度:O(6) => 常數
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.