检查数组中的所有对是否都能被 k 整除
Check whether all the pairs in an array are divisible by k
给定一个整数数组和一个数字
k
,编写一个返回 true 的函数,如果给定的数组可以分成对,使得每对的总和可以被k
整除。
这段代码为所有测试用例生成正确的结果,除了我找不到其中的故障。
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int k;
cin >> k;
int flag[n] = {0};
int p = 0;
int q = 0;
if (n % 2 != 0) {
cout << "False" << endl;
} else {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((arr[i] + arr[j]) % k == 0 && flag[j] == 0) {
p = 1;
flag[j] = 1;
}
}
if (p == 0) {
q = 1;
cout << "False" << endl;
break;
}
}
if (q == 0) {
cout << "True" << endl;
}
}
}
return 0;
}
代码中错误的主要来源之一是混乱的代码。那么我们如何清理代码呢?我们将其模块化。这意味着分解代码,以便代码的每个部分都能很好地完成一项工作。让我们看看它是什么样子的。
检查某物是否可以被 k 整除的函数:
bool isDivisible(int number, int divisor) {
return number % divisor == 0;
}
检查所有货币对的功能:逻辑如下:
- 取列表中的第一个号码;
n0
拨打。 - 对于每个剩余的数
n1
,检查它加上第一个数是否可以被 k 整除 - 当我们发现
n1
n0 + n1
可以被k
整除时,一个。如果剩余的数字也可以拆分成可整除对,则返回 trueb.否则,请继续搜索
4.如果我们已经搜索了所有数字,则返回 false。
bool pairsDivisible(int* nums, int count, int k) {
if(count == 0) return true;
if(count % 2 != 0) return false; // count must be even
// 1.
int n0 = nums[0];
// 2.
for(int i = 1; i < count; i++) {
int n1 = nums[i];
// 3.
if(isDivisible(n0 + n1, k)) {
// Move the ith number so it's now nums[1]
std::swap(nums[1], nums[i]);
if(pairsDivisible(nums + 2, count - 2, k)) {
return true; // 3.a
} else {
// Reset the array
std::swap(nums[1], nums[i]);
}
}
}
return false;
}
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 用于检查数字是否有数字或可被该数字的值整除的程序
- 检查数组中的所有对是否都能被 k 整除
- 创建一个程序来告诉用户一个数字是否可以被 5 整除
- 是否有按位技巧来检查数字被 2 或 3 整除
- 当对可被7整除的向量大小进行排序时,是否有什么东西会导致快速排序算法出错
- 是否有可能编写一个函数模板来返回参数的数量是否能被N整除?
- 算出一个很大的数是否能被另一个数整除
- 如何在c++中检查一个数字是否可以被2*M_PI整除