搜索
首页后端开发C++检查是否有任何有效的序列可以被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中文网其他相关文章!

声明
本文转载于:tutorialspoint。如有侵权,请联系admin@php.cn删除
继续使用C:耐力的原因继续使用C:耐力的原因Apr 11, 2025 am 12:02 AM

C 持续使用的理由包括其高性能、广泛应用和不断演进的特性。1)高效性能:通过直接操作内存和硬件,C 在系统编程和高性能计算中表现出色。2)广泛应用:在游戏开发、嵌入式系统等领域大放异彩。3)不断演进:自1983年发布以来,C 持续增加新特性,保持其竞争力。

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 09, 2025 am 12:06 AM

现代C 设计模式利用C 11及以后的新特性实现,帮助构建更灵活、高效的软件。1)使用lambda表达式和std::function简化观察者模式。2)通过移动语义和完美转发优化性能。3)智能指针确保类型安全和资源管理。

C多线程和并发:掌握并行编程C多线程和并发:掌握并行编程Apr 08, 2025 am 12:10 AM

C 多线程和并发编程的核心概念包括线程的创建与管理、同步与互斥、条件变量、线程池、异步编程、常见错误与调试技巧以及性能优化与最佳实践。1)创建线程使用std::thread类,示例展示了如何创建并等待线程完成。2)同步与互斥使用std::mutex和std::lock_guard保护共享资源,避免数据竞争。3)条件变量通过std::condition_variable实现线程间的通信和同步。4)线程池示例展示了如何使用ThreadPool类并行处理任务,提高效率。5)异步编程使用std::as

C深度潜水:掌握记忆管理,指针和模板C深度潜水:掌握记忆管理,指针和模板Apr 07, 2025 am 12:11 AM

C 的内存管理、指针和模板是核心特性。1.内存管理通过new和delete手动分配和释放内存,需注意堆和栈的区别。2.指针允许直接操作内存地址,使用需谨慎,智能指针可简化管理。3.模板实现泛型编程,提高代码重用性和灵活性,需理解类型推导和特化。

C和系统编程:低级控制和硬件交互C和系统编程:低级控制和硬件交互Apr 06, 2025 am 12:06 AM

C 适合系统编程和硬件交互,因为它提供了接近硬件的控制能力和面向对象编程的强大特性。1)C 通过指针、内存管理和位操作等低级特性,实现高效的系统级操作。2)硬件交互通过设备驱动程序实现,C 可以编写这些驱动程序,处理与硬件设备的通信。

使用C的游戏开发:构建高性能游戏和模拟使用C的游戏开发:构建高性能游戏和模拟Apr 05, 2025 am 12:11 AM

C 适合构建高性能游戏和仿真系统,因为它提供接近硬件的控制和高效性能。1)内存管理:手动控制减少碎片,提高性能。2)编译时优化:内联函数和循环展开提升运行速度。3)低级操作:直接访问硬件,优化图形和物理计算。

C语言文件操作难题的幕后真相C语言文件操作难题的幕后真相Apr 04, 2025 am 11:24 AM

文件操作难题的真相:文件打开失败:权限不足、路径错误、文件被占用。数据写入失败:缓冲区已满、文件不可写、磁盘空间不足。其他常见问题:文件遍历缓慢、文本文件编码不正确、二进制文件读取错误。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)