B. Raspberries
B. Raspberries
You are given an array of integers and a number (). In one operation, you can do the following:
- Choose an index ,
- Set .
Find the minimum number of operations needed to make the product of all the numbers in the array divisible by .
Input
Each test consists of multiple test cases. The first line contains a single integer () — the number of test cases. Then follows the description of the test cases.
The first line of each test case contains two integers and (, ) — the size of the array and the number .
The second line of each test case contains integers ().
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output the minimum number of operations needed to make the product of all the numbers in the array divisible by .
Example
input
15
2 5
7 3
3 3
7 4 1
5 2
9 7 7 3 9
5 5
5 4 1 2 3
7 4
9 5 1 5 9 5 1
3 4
6 3 6
3 4
6 1 5
3 4
1 5 9
4 4
1 4 1 1
3 4
3 5 3
4 5
8 9 9 3
2 5
1 6
2 5
10 10
4 5
1 6 1 1
2 5
7 7
output
2
2
1
0
2
0
1
2
0
1
1
4
0
4
3
Note
In the first test case, we need to choose the index twice. After that, the array will be . The product of all the numbers in the array is .
In the fourth test case, the product of the numbers in the array is , which is already divisible by , so no operations are needed.
In the eighth test case, we can perform two operations by choosing and in any order. After that, the array will be . The product of the numbers in the array is .
解题思路
昨天两场掉大分,好似喵。这题卡了我快 个小时,心态直接炸了。即便后面还是坚持做出来 题排名还是基本垫底。
很小直接分类讨论,当时逻辑很乱都不知道在想什么。
当 ,那么只要数组中有一个数是 的倍数,答案就是 。否则考虑将一个数加成 的倍数为止。很明显只对一个数进行操作是最优解,因为我们只需让这些数中有一个是 的倍数即可。对于某个数 ,若要将其变成 的倍数那么最少需要操作 次。
当 ,与上面的方法相同,不过还要考虑另外一种情况。因为 ,因此如果数组中存在至少两个偶数,那么答案是 (当然只有一个 也可以,不过这种情况已经用上面的方法判掉了)。否则我们可以通过一次操作将一个奇数变偶数,因此最多选择两个奇数进行操作。假设数组中有 个偶数,那么就要执行 次操作。注意,要特判 的情况。
AC 代码如下,时间复杂度为 :
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
void solve() {
int n, k;
scanf("%d %d", &n, &k);
int ret = 1e9, c = 0;
for (int i = 0; i < n; i++) {
int x;
scanf("%d", &x);
ret = min(ret, k - 1 - (x - 1) % k);
if (~x & 1) c++;
}
if (k == 4 && n > 1) ret = min(ret, max(0, 2 - c));
printf("%d\n", ret);
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
solve();
}
return 0;
}
参考资料
Codeforces Round #905 (Div. 1, Div. 2, Div. 3) Editorial:https://codeforces.com/blog/entry/121621
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/17783279.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2022-10-23 A. Bestie
2022-10-23 三元组