簡體   English   中英

對於這個,有什么比蠻力更好的解決方案?

[英]What is a better solution than brute force for this?

給定[0-5]之間有限的正整數序列,假設[0,3,1,5,2,4,4,4]和起始序列[0,0,0,0,0,0,0 ,0]。 我們現在想要通過執行逐步操作從起始序列構建我們給定的序列。 在一個步驟中,我們可以將起始序列中的所有數字增加1,或者將此序列中的一個索引增加1.一旦我們在這種情況下增加5,它將變為0。

找到需要最少步驟的解決方案的最有效方法是什么? 這個解決方案當然也應該適用於其他輸入(長度+上限)。 對於起始序列,我們可以假設每個索引始終為0。

蠻力方法看起來像這樣。

int upperBound = 5;
int[] endSequence = {0,3,1,5,2,4,4,4};
int currentBestSteps = Integer.MAX_VALUE;
int currentTimesIncreaseAll = 0;

for(int start = 0;start <= upperBound;start++){ //how many times to increase all
  //counter how many steps required total, starting with start amount of steps
  //since we increase all values 'start' times  
  int counterSteps = start; 

  //go through all end values and calc how many steps required  
  for(int end:endSequence){ 
    if(start <= end){
      counterSteps += end-start;
    }else{
      counterSteps += end+upperBound+1-start;
    }
  }

  System.out.println("solution: increase all "+start+
                     " times, total steps: "+counterSteps);

  if(counterSteps < currentBestSteps){
    currentBestSteps = counterSteps;
    currentTimesIncreaseAll = start;
  }
}
System.out.println("best solution: increase all "+currentTimesIncreaseAll+
                   " times, total steps: "+currentBestSteps);

結果:

solution: increase all 0 times, total steps: 23
solution: increase all 1 times, total steps: 22
solution: increase all 2 times, total steps: 21
solution: increase all 3 times, total steps: 20
solution: increase all 4 times, total steps: 19
solution: increase all 5 times, total steps: 30
best solution: increase all 4 times, total steps: 19

我將提供一種方法來減少目標原始數組(稱之為A )以生成[0,0,0,0...] ,方法是遞減所有內容或遞減單個項目。 這當然是同樣的問題,但反過來的步驟。

首先,計算逐個遞減所有元素的成本。 將此成本稱為CMAX和數組N的長度。 CMAX = sum_for_all_i(A [i])

然后對數組進行排序,並找到每個位置i,其中i = 0A [1]> A [I-1]。

對於每個這樣的位置,很容易計算在A [i]達到0之前減少所有內容所產生的成本, 然后逐個遞減。 這很容易,因為我們知道索引<i的所有內容都會回滾,而索引> = i的所有東西都不會。 所以:

COST(i)= CMAX + A [i] - A [i] *(Ni)+ i *(UPPER_BOUND + 1-A [i])

A [i]是所有全局減量的代價。 -A [i] *(Ni)是所有不包裹的高元素的成本降低,成本i *(UPPER_BOUND + 1-A [i])是所有元素的成本增加從0UPPER_BOUND回繞

您找到的最低成本 (包括CMAX )就是您的答案。 總復雜度為O(N log N) ,由排序主導。 如果上限保證很小,那么你可以使用計數排序並得到O(N + k)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM