D. Exam in MAC
D. Exam in MAC
The Master's Assistance Center has announced an entrance exam, which consists of the following.
The candidate is given a set of size and some strange integer . For this set, it is needed to calculate the number of pairs of integers such that , is not contained in the set , and also is not contained in the set .
Your friend wants to enter the Center. Help him pass the exam!
Input
Each test consists of multiple test cases. The first line contains a single integer () — the number of test cases. The description of the test cases follows.
The first line of each test case contains two integers and (, ) — the size of the set and the strange integer.
The second line of each test case contains integers () — the elements of the set .
It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output a single integer — the number of suitable pairs of integers.
Example
input
8
3 3
1 2 3
1 179
57
4 6
0 3 5 6
1 1
1
5 10
0 2 4 8 10
5 10
1 3 5 7 9
4 10
2 4 6 7
3 1000000000
228 1337 998244353
output
3
16139
10
2
33
36
35
499999998999122959
Note
In the first test case, the following pairs are suitable: , , .
In the third test case, the following pairs are suitable: , , , , , , , , , .
解题思路
正着不好算,考虑容斥原理反过来做。用总的数对,减去满足 的数对数量,减去 的数对数量,最后加上同时满足 且 的数对数量,就是要求的答案。
其中总的数对就是 。
满足 的数对数量。由于 且 ,则有 ,解得 。由于 与 一一对应,因此只用考虑 的数量,即 。由于每个 都不同,因此总的数对数量就是 。
满足 的数对数量。同理解得 ,总的数对数量就是 。
同时满足 且 的数对数量。意味着同一个数对 被减了 次,即满足 , 可以等于 。有 ,,意味着 和 的奇偶性要相同。假设有 个偶数的 , 奇数的 ,那么数对数量就是 。
AC 代码如下,时间复杂度为 :
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 3e5 + 10;
int a[N];
void solve() {
int n, m;
scanf("%d %d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%d", a + i);
}
LL ret = (m + 1ll) * (m + 2ll) / 2;
int c0 = 0, c1 = 0;
for (int i = 0; i < n; i++) {
ret -= a[i] / 2 + 1 + m - a[i] + 1;
if (a[i] & 1) c1++;
else c0++;
}
ret += c0 * (c0 + 1ll) / 2 + c1 * (c1 + 1ll) / 2;
printf("%lld\n", ret);
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
solve();
}
return 0;
}
参考资料
Codeforces Round #932 (Div. 2) Editorial:https://codeforces.com/blog/entry/126662
本文来自博客园,作者:onlyblues,转载请注明原文链接:https://www.cnblogs.com/onlyblues/p/18056900
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效
2022-03-06 正则问题
2022-03-06 树的DFS