目錄
問題陳述
範例 2
方法 1:暴力方法
虛擬程式碼
範例:C 實作
輸出
方法 2:回溯
方法 3:貪婪方法
方法 4:動態規劃
結論
首頁 後端開發 C++ 檢查是否有任何有效的序列可以被M整除

檢查是否有任何有效的序列可以被M整除

Sep 11, 2023 pm 02:37 PM
檢查有效序列 整除判定 m序列

檢查是否有任何有效的序列可以被M整除

序列是物件的集合,在我們的例子中,它是整數的集合。任務是判斷元素內使用加減運算子的序列是否能被 M 整除。

問題陳述

給定一個整數 M 和一個整數陣列。僅使用元素之間的加法和減法檢查是否存在其解可被 M 整除的有效序列。

範例 1

Input: M = 2, arr = {1, 2, 5}
登入後複製
Output: TRUE
登入後複製

解釋 - 對於給定的數組,可能存在有效序列 {1 2 5} = {8},且可被 2 整除。

範例 2

Input: M = 4, arr = {1, 2}
登入後複製
Output: FALSE
登入後複製

解釋 - 對於給定的數組,不可能存在其解可被 4 整除的序列。

方法 1:暴力方法

解決這個問題的簡單方法是使用遞歸函數來尋找陣列的所有可能序列,然後檢查是否有任何序列可被 M 整除。

虛擬程式碼

procedure divisible (M, arr[], index, sum, n)
   if index == n
      if sum is a multiple of M
         ans = TRUE
      end if
      ans = false
   end if
   divisible(M, arr, index + 1, sum + arr[index], n) or divisible(M, arr, index + 1, sum - arr[index], n)
end procedure
登入後複製

範例:C 實作

在下面的程式中,我們使用遞歸方法來尋找所有有效序列,然後檢查是否有任何有效序列可被 M 整除。

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

// Recusive function to find if a valid sequence is divisible by M or not
bool divisible(int M, int arr[], int index, int sum, int n){

   // Cheking the divisiblilty by M when the array ends
   if (index == n)  {
      if (sum % M == 0){
         return true;
      }
      return false;
   }
   
   // If either of addition or subtraction is true, return true
   return divisible(M, arr, index + 1, sum + arr[index], n) || divisible(M, arr, index + 1, sum - arr[index], n);
}
int main(){
   int M = 4, arr[2] = {1, 5};
   if (divisible(M, arr, 0, 0, 2)){
      cout << "TRUE";
   }
   else{
      cout << " FALSE";
   }
   return 0;
}
登入後複製

輸出

TRUE
登入後複製
登入後複製
登入後複製
登入後複製

時間複雜度 - O(2^n) 由於使用了遞迴。

空間複雜度 - O(n) 由於遞歸堆疊空間。

方法 2:回溯

此方法類似於先前的強力遞歸方法,不同之處在於使用回溯,我們可以回溯搜尋空間,以免走上我們知道不具有可被 M 整除的有效序列的路徑。

虛擬程式碼

procedure divisible (M, arr[], index, sum, n)
   if index == n
      if sum is a multiple of M
         ans = TRUE
      end if
      ans = false
   end if
   if divisible(M, arr, index + 1, sum + arr[index], n)
      ans = true
   end if
   if divisible(M, arr, index + 1, sum - arr[index], n)
      ans = true
   end if
   ans = false
end procedure
登入後複製

範例:C 實作

在下面的程式中,我們使用回溯來修剪搜尋空間,以找到問題的解決方案。

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

// Function to find if a valid sequence is divisible by M or not
bool divisible(int M, int arr[], int index, int sum, int n){

   // Cheking the divisiblilty by M when the array ends
   if (index == n){
      if (sum % M == 0){
         return true;
      }
      return false;
   }
   
   // Checking the divisibility of sum + arr[index]
   if (divisible(M, arr, index + 1, sum + arr[index], n)){
      return true;
   }
   
   // Checking the divisibility of sum - arr[index]
   if (divisible(M, arr, index + 1, sum - arr[index], n)){
      return true;
   }
   return false;
}
int main(){
   int M = 4, arr[2] = {1, 5};
   if (divisible(M, arr, 0, 0, 2)){
      cout << "TRUE";
   }
   else{
      cout << " FALSE";
   }
   return 0;
}
登入後複製

輸出

TRUE
登入後複製
登入後複製
登入後複製
登入後複製

時間複雜度 - 最壞情況下的時間複雜度為 O(2^n),但實際上由於搜尋空間的修剪,它比暴力方法更好。

空間複雜度 - 由於遞歸堆疊空間而導致的 O(n)。

方法 3:貪婪方法

這個問題的貪心解法是先將陣列依升序排序,然後在總和不超過 M 的情況下貪婪地應用加法函數。這種方法可能不會給出全域最優解,但會給出局部最優解。

虛擬程式碼

procedure divisible (M, arr[])
   sum = 0
   for i = 1 to end of arr
      sum = sum + arr[i]
   if sum is divisible by M
      ans = true
   end if
   sort array arr[]
   i = 0
   j = last index of array
   while i < j
      if arr[j] - arr[i] is divisible by M
         ans = true
      end if
      if sum % M == (sum - arr[j]) % M
         sum = sum - arr[j]
         j = j - 1
      else
         sum = sum - arr[i]
         i = i + 1
      end if
   ans = false
end procedure
登入後複製

範例:C 實作

在下面的程式中,將陣列進行排序以找到可被 M 整除的最佳局部子陣列。

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

// Greedy function to find if a valid sequence is divisible by M or not
bool divisible(int M, vector<int> &arr){
   int sum = 0;
   for (int i = 0; i < arr.size(); i++) {
      sum += arr[i];
   }
   
   // Checking if sumof all elements is divisible by M
   if (sum % M == 0){
      return true;
   }
   
   sort(arr.begin(), arr.end());
   int i = 0, j = arr.size() - 1;
   while (i < j){
   
      // Checking if the difference between the largest and smallest element at a time in the array is divisible by M
      if ((arr[j] - arr[i]) % M == 0){
         return true;
      }
      
      // Removing either the largest or smallest element based on which does not affect the sum's divisibility
      if (sum % M == (sum - arr[i]) % M){
         sum -= arr[i];
         i++;
      }
      else{
         sum -= arr[j];
         j--;
      }
   }
   return false;
}
int main(){
   int M = 4;
   int array[2] = {1, 3};
   vector<int> arr(array, array + 2);
   if (divisible(M, arr)){
      cout << "TRUE";
   }
   else{
      cout << " FALSE";
   }
   return 0;
}
登入後複製

輸出

TRUE
登入後複製
登入後複製
登入後複製
登入後複製

方法 4:動態規劃

使用動態規劃的概念,在此解決方案中我們儲存評估的中間結果。我們將建立一個包含 N 1 行和 M 列的表,並且當我們不使用陣列元素時,結果 % M == 0 的基本情況。然後迭代模 M 的所有可能餘數,我們更新表格。

虛擬程式碼

procedure divisible (arr[], M , N)
   dp[N+1][M] = false
   dp[0][0] = true 
   for i = 1 to N
      for i = j to M
         mod = arr[ i- 1] % M
         dp[i][j] = dp[i - 1][(j - mod + M) % M] or dp[i - 1][(j + mod) % M]
   ans = dp[N][0]
end procedure
登入後複製

範例:C 實作

在下面的程式中,我們將問題分解為子問題,然後解決它們。

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

// Function to find if a valid sequence is divisible by M or not
bool divisible(int arr[], int M, int N){

   // Creating the dp table of size N+1 * M
   vector<vector<bool> > dp(N + 1, vector<bool>(M, false));
   
   // Base case
   dp[0][0] = true;
   
   // For each element iterating over all possible remainders j modulo M
   for (int i = 1; i <= N; i++){
      for (int j = 0; j < M; j++){
         int mod = arr[i - 1] % M;
         
         // Either exclude or include the current element in the table
         dp[i][j] = dp[i - 1][(j - mod + M) % M] || dp[i - 1][(j + mod) % M];
      }
   }
   return dp[N][0];
}
int main(){
   int M = 4;
   int arr[2] = {1, 3};
   if (divisible(arr, M, 2)){
      cout << "TRUE";
   }
   else{
      cout << " FALSE";
   }
   return 0;
}
登入後複製

輸出

TRUE
登入後複製
登入後複製
登入後複製
登入後複製

結論

總而言之,為了找到可被M 整除的有效序列,我們可以應用多種方法以及不同的關係和空間分析,範圍從暴力情況下的O(2^n) 到動態情況下的O(NM)程式設計是最有效的方法。

以上是檢查是否有任何有效的序列可以被M整除的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1664
14
CakePHP 教程
1422
52
Laravel 教程
1316
25
PHP教程
1268
29
C# 教程
1240
24
C#與C:歷史,進化和未來前景 C#與C:歷史,進化和未來前景 Apr 19, 2025 am 12:07 AM

C#和C 的歷史與演變各有特色,未來前景也不同。 1.C 由BjarneStroustrup在1983年發明,旨在將面向對象編程引入C語言,其演變歷程包括多次標準化,如C 11引入auto關鍵字和lambda表達式,C 20引入概念和協程,未來將專注於性能和系統級編程。 2.C#由微軟在2000年發布,結合C 和Java的優點,其演變注重簡潔性和生產力,如C#2.0引入泛型,C#5.0引入異步編程,未來將專注於開發者的生產力和雲計算。

C和XML的未來:新興趨勢和技術 C和XML的未來:新興趨勢和技術 Apr 10, 2025 am 09:28 AM

C 和XML的未來發展趨勢分別為:1)C 將通過C 20和C 23標準引入模塊、概念和協程等新特性,提升編程效率和安全性;2)XML將繼續在數據交換和配置文件中佔據重要地位,但會面臨JSON和YAML的挑戰,並朝著更簡潔和易解析的方向發展,如XMLSchema1.1和XPath3.1的改進。

繼續使用C:耐力的原因 繼續使用C:耐力的原因 Apr 11, 2025 am 12:02 AM

C 持續使用的理由包括其高性能、廣泛應用和不斷演進的特性。 1)高效性能:通過直接操作內存和硬件,C 在系統編程和高性能計算中表現出色。 2)廣泛應用:在遊戲開發、嵌入式系統等領域大放異彩。 3)不斷演進:自1983年發布以來,C 持續增加新特性,保持其競爭力。

C#vs. C:學習曲線和開發人員的經驗 C#vs. C:學習曲線和開發人員的經驗 Apr 18, 2025 am 12:13 AM

C#和C 的学习曲线和开发者体验有显著差异。1)C#的学习曲线较平缓,适合快速开发和企业级应用。2)C 的学习曲线较陡峭,适用于高性能和低级控制的场景。

C和XML:探索關係和支持 C和XML:探索關係和支持 Apr 21, 2025 am 12:02 AM

C 通過第三方庫(如TinyXML、Pugixml、Xerces-C )與XML交互。 1)使用庫解析XML文件,將其轉換為C 可處理的數據結構。 2)生成XML時,將C 數據結構轉換為XML格式。 3)在實際應用中,XML常用於配置文件和數據交換,提升開發效率。

現代C設計模式:構建可擴展和可維護的軟件 現代C設計模式:構建可擴展和可維護的軟件 Apr 09, 2025 am 12:06 AM

現代C 設計模式利用C 11及以後的新特性實現,幫助構建更靈活、高效的軟件。 1)使用lambda表達式和std::function簡化觀察者模式。 2)通過移動語義和完美轉發優化性能。 3)智能指針確保類型安全和資源管理。

C社區:資源,支持和發展 C社區:資源,支持和發展 Apr 13, 2025 am 12:01 AM

C 學習者和開發者可以從StackOverflow、Reddit的r/cpp社區、Coursera和edX的課程、GitHub上的開源項目、專業諮詢服務以及CppCon等會議中獲得資源和支持。 1.StackOverflow提供技術問題的解答;2.Reddit的r/cpp社區分享最新資訊;3.Coursera和edX提供正式的C 課程;4.GitHub上的開源項目如LLVM和Boost提陞技能;5.專業諮詢服務如JetBrains和Perforce提供技術支持;6.CppCon等會議有助於職業

超越炒作:評估當今C的相關性 超越炒作:評估當今C的相關性 Apr 14, 2025 am 12:01 AM

C 在現代編程中仍然具有重要相關性。 1)高性能和硬件直接操作能力使其在遊戲開發、嵌入式系統和高性能計算等領域佔據首選地位。 2)豐富的編程範式和現代特性如智能指針和模板編程增強了其靈活性和效率,儘管學習曲線陡峭,但其強大功能使其在今天的編程生態中依然重要。

See all articles