Educational Codeforces Round 115 (Rated for Div. 2) D 容斥定理 组合数学

题目

Monocarp 是伯兰州立大学编程团队的教练。他决定为他的团队的培训课程编写问题集。

Monocarp 有 n 个他的学生还没有见过的问题。第 i 个问题有一个主题 ai(一个从 1 到 n 的整数)和一个难度 bi(一个从 1 到 n 的整数)。所有的问题都是不同的,即不存在同时具有相同主题和难度的两个任务。

Monocarp 决定从 n 个问题中为问题集中选择 3 个问题。问题应至少满足以下两个条件之一(可能同时满足):
三道选题的题目都不一样;
三道选定题的难度各不相同。
您的任务是确定为问题集选择三个问题的方法数。

输入
第一行包含一个整数 t (1≤t≤50000)——测试用例的数量。
每个测试用例的第一行包含一个整数 n (3≤n≤2⋅105) —— Monocarp 遇到的问题数量。
在下面n行的第i行中,有两个整数ai和bi(1≤ai,bi≤n)——第i个问题的题目和难度。
保证不存在同一主题、同一难度的两道题。
所有测试用例的 n 总和不超过 2⋅105。

输出
打印选择满足语句中描述的任一要求的三个训练问题的方法数。

题解思路

题目让我们找到保证不存在 ai == aj || bi == bj 的情况 。
逆否命题就是 存在 一个 ai == aj 或者 bi == bj 。
Educational Codeforces Round 115 (Rated for Div. 2) D 容斥定理 组合数学_第1张图片
列出总数
我们枚举每个N 减去 逆否命题的情况 即存在相同的a或者b 。

        for (int i = 1 ; i <= n ; i++ )
        {
     
            ans -=  (long long )1 *( ca[a[i]] - 1 ) * ( cb[b[i]] - 1 ) ;
        }

AC代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const  int  INF =  0x3f3f3f3f;
const  int N = 200100 ;

int a[N] , b[N] ;
int ca[N] , cb[N] ;

int main ()
{
     
    ios::sync_with_stdio(false);
    int T;
    cin >> T ;
    while ( T -- )
    {
     
        long long ans = 0 ;
        int n ;
        cin >> n ;
        for (int i = 1 ; i <= n ; i++ )
            ca[i] = 0 , cb[i] = 0 ;

        for (int i = 1 ; i <= n ; i++ )
        {
     
            cin >> a[i] >> b[i] ;
            ca[a[i]]++ , cb[b[i]]++ ;
        }

        ans = (long long) n * (n-1)*(n-2) / 6 ;

        for (int i = 1 ; i <= n ; i++ )
        {
     
            ans -=  (long long )1 *( ca[a[i]] - 1 ) * ( cb[b[i]] - 1 ) ;
        }
        cout << ans << "\n" ;
    }
    return 0 ;
}

你可能感兴趣的:(数论,算法)