C++ 程式在不爆炸的情況下找到將金塊載入到體重秤上的順序


假設我們有一個包含 n 個不同元素的陣列 A,以及另一個數字 x。有 n 塊金塊。第 i 塊金塊的重量為 A[i]。我們將這 n 塊金塊逐個放入體重秤中。但這個體重秤有一個不尋常的缺陷:如果它上的總重量恰好為 x,它就會爆炸。我們必須檢查是否可以在不爆炸體重秤的情況下,按照某種順序將所有 n 塊金塊放入體重秤中。如果可以,找到該順序。如果不行,則標記為“不可能”。

因此,如果輸入類似於 A = [1, 2, 3, 4, 8];x = 6,則輸出將為 [8, 1, 2, 3, 4],其他順序也同樣有效

步驟

要解決這個問題,我們將遵循以下步驟:

s := 0
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do:
   s := s + A[i]
if s is same as x, then:
   return "IMPOSSIBLE"
s := 0
for initialize i := 0, when i < n, update (increase i by 1), do:
   s := s + A[i]
   if s is same as x, then:
      print A[i + 1], A[i]
      (increase i by 1)
      Ignore following part, skip to the next iteration
   print A[i]

示例

讓我們看看以下實現來更好地理解:

#include <bits/stdc++.h>
using namespace std;

void solve(vector<int> A, int x) {
   int s = 0;
   int n = A.size();
   for (int i = 0; i < n; i++) {
      s += A[i];
   }
   if (s == x) {
      cout << "IMPOSSIBLE";
      return;
   }
   s = 0;
   for (int i = 0; i < n; i++) {
      s += A[i];
      if (s == x) {
         cout << A[i + 1] << ", " << A[i] << ", ";
         i++;
         continue;
      }
      cout << A[i] << ", ";
   }
}
int main() {
   vector<int> A = { 1, 2, 3, 4, 8 };
   int x = 6;
   solve(A, x);
}

輸入

{ 1, 2, 3, 4, 8 }, 6

輸出

1, 2, 4, 3, 8,

更新於: 03-Mar-2022

103 次瀏覽

開啟您的 事業

完成課程以獲得認證

開始
插播廣告
© . All rights reserved.