题意
每一次询问给出一个集合 和一个整数 ,问有多少对 满足 且 和 都不在集合 里。
题解
条件1
先只考虑 这个条件,想一想可知一共有 种情况(对应我代码中的 _f1 函数),记为满足条件 下的数量。
条件2
然后考虑 且 的情况。对于每一个在 中的数 ,考虑 :
一共 种情况(对应我代码中的 _f2 函数),记为满足条件 下的数量(取所有 之和)。
条件3
考虑 且 的情况。对于每一个在 中的数 ,考虑 :
一共 种情况(对应我代码中的 _f3 函数),记为满足条件 下的数量(取所有 之和)
条件4
考虑 且 且 的情况。设 且 :
也就是说 的奇偶性相同。记集合 中有 个偶数,那么在这种条件下应该有 种情况。考虑到 个奇数的话一共就是 种情况(对应我代码中的 _f4 函数),记为满足条件 下的数量。
加总
现在来考虑原题目条件。既然要求 和 都不在集合 中,那么就要从满足条件 下的数量中分别扣除满足条件 下和满足条件 下的数量;同时加上被重复计算的满足条件 下的数量。(容斥原理)
代码:
#include<iostream>
using namespace std;
long long s[300001];
int n;
long long c;
//这些函数刚刚解释过了
inline long long _f1(long long x){
return (x+1)*(x+1)-(x+1)*x/2;
}
inline long long _f2(long long x){
return x-(x+x%2)/2+1;
}
inline long long _f3(long long x){
return (c-x+1);
}
inline long long _f4(long long x){
return (x*(x+1)/2+(n-x)*(n-x+1)/2);
}
int main(){
int T;
cin >> T;
while(T--){
long long cnt1=0;
cin >> n >> c;
for(int i=1;i<=n;i++){
cin >> s[i];
if(s[i]%2==0) ++cnt1;
}
long long ans=_f1(c);
for(int i=1;i<=n;i++){
//枚举集合中的每一个元素并分别扣除
ans-=_f2(s[i]);
ans-=_f3(s[i]);
}
ans=ans+_f4(cnt1);
cout << ans << '\n';
}
return 0;
}