CF1935D题解

· · 题解

题意

每一次询问给出一个集合 s 和一个整数 c,问有多少对 (x,y) 满足 0 \le x \le y \le c 且 x+y 和 y-x 都不在集合 s 里。

题解

条件1

先只考虑 0 \le x \le y \le c 这个条件,想一想可知一共有 (c+1)^2-\frac{1}{2}c(c+1) 种情况(对应我代码中的 _f1 函数),记为满足条件 1 下的数量。

条件2

然后考虑 0 \le x \le y \le c 且 x+y \in s 的情况。对于每一个在 s 中的数 a,考虑 x+y=a:

\because a-y=x \le y\\ \therefore \lceil\frac{a}{2}\rceil \le y \le a\\

一共 a-\lceil\frac{a}{2}\rceil+1 种情况(对应我代码中的 _f2 函数),记为满足条件 2 下的数量(取所有 a \in s 之和)。

条件3

考虑 0 \le x \le y \le c 且 y-x \in s 的情况。对于每一个在 s 中的数 a,考虑 y-x=a:

\because 0 \le x+a=y \le c\\ \therefore 0 \le x+a \le c\\ \therefore 0 \le x \le c-a

一共 c-a+1 种情况(对应我代码中的 _f3 函数),记为满足条件 3 下的数量(取所有 a \in s 之和)

条件4

考虑 0 \le x \le y \le c 且 x+y \in s 且 y-x \in s 的情况。设 y-x=a 且 x+y=b:

\because a+b=(y-x)+(x+y)=2y\\ \therefore 2 \mid a+b

也就是说 a+b 的奇偶性相同。记集合 s 中有 x 个偶数,那么在这种条件下应该有 \frac{1}{2}x(x+1) 种情况。考虑到 c-x 个奇数的话一共就是 \frac{1}{2}x(x+1)+\frac{1}{2}(c-x)(c-x+1) 种情况(对应我代码中的 _f4 函数),记为满足条件 4 下的数量。

加总

现在来考虑原题目条件。既然要求 x+y 和 y-x 都不在集合 s 中,那么就要从满足条件 1 下的数量中分别扣除满足条件 2 下和满足条件 3 下的数量;同时加上被重复计算的满足条件 4 下的数量。(容斥原理)

代码:

#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;
}