C++ 中可重新排列形成迴文子陣列的計數


給定一個整數元素陣列,任務是計算可以從給定陣列中形成的子陣列的數量,使得其元素可以形成一個有效的迴文。迴文是從開頭到結尾排列方式相同的序列。

輸入 − int arr[] = { 3, 3, 1, 4, 2, 1, 5}

輸出 − 可重新排列形成迴文的子陣列數量為 − 9

解釋 − 元素可以排列成迴文的有效子陣列為 {3}, {3}, {1}, {4}, {2}, {1}, {5}, {1, 2, 1} 和 {1, 3, 1}。因此,總數為 9。

輸入 − int arr[] = { 2, 5, 5, 2, 1}

輸出 − 可重新排列形成迴文的子陣列數量為 − 8

解釋 − 元素可以排列成迴文的有效子陣列為 {2}, {5}, {5}, {2}, {1}, {5, 2, 5}, {2, 5, 2}, {2, 5, 5, 2}。因此,總數為 8。

下面程式中使用的方案如下

  • 輸入一個整數元素陣列,並計算陣列的大小,並將資料傳遞給函式以進行進一步處理。

  • 宣告一個臨時變數 count 來儲存迴文子陣列。

  • 從 0 到陣列大小開始 FOR 迴圈

  • 在迴圈內部,宣告一個 long long 型別的變數並將其設定為 1LL << arr[j],並將 temp 設定為 temp ^ val

  • 在布林變數內部呼叫一個函式,該函式將返回 true 或 false。

  • 檢查 IF temp 為 0LL 或 ch 為 True,則將 count 加 1

  • 返回 count

  • 列印結果。

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
bool check(long long temp){
   return !(temp & (temp - 1LL));
}
int palindromes_rearrange(int arr[], int size){
   int count = 0;
   for (int i = 0; i < size; i++){
      long long temp = 0LL;
      for (int j = i; j < size; j++){
         long long val = 1LL << arr[j];
         temp = temp ^ val;
         bool ch = check(temp);
         if (temp == 0LL || ch){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int arr[] = { 3, 3, 1, 4, 2, 1, 5};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of sub-arrays whose elements can be re-arranged to form palindromes are:
"<<palindromes_rearrange(arr, size);
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Count of sub-arrays whose elements can be re-arranged to form palindromes are: 9

更新於: 2020-12-02

224 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.