本文共 1073 字,大约阅读时间需要 3 分钟。
为了解决这个问题,我们需要找到一个最短的子数组,使得子数组的和不能整除给定的数x。如果不存在这样的子数组,则返回-1。
#include#include using namespace std;int main() { int t; cin >> t; while (t--) { int n, x; cin >> n >> x; vector a(n); bool has_non_divisible = false; for (int num : a) { if (num % x != 0) { has_non_divisible = true; break; } } if (has_non_divisible) { cout << 1; continue; } long long sum_total = 0; for (int num : a) { sum_total += num; } if (sum_total % x != 0) { cout << n; } else { cout << -1; } }}
这种方法确保我们在O(n)的时间复杂度内解决问题,高效且直接。
转载地址:http://cfnt.baihongyu.com/