Codeforces C. Ball in Berland (#697 Div.3) (思维 | 容斥原理)

传送门

题意: 现有 k 组男女,总共包含 a 个男孩和 b 个女孩;从中任意选出两组男女,保证男女不会重复出现在该两组,试问有多少总取法?
输入:先输入 a b k ,再输入一行男孩和一行女孩(一一对应为一组)。
在这里插入图片描述

思路:

  • 方法1 (思维) : 当前男孩 a[i] 对答案ans的贡献为 k - 当前男孩 a[i] 匹配的女孩数 - 当前女孩 b[i] 匹配的男孩数 + 1 (当前的<a[i],b[i]>组合被剪了两次);又因为每次 第 i 组和第 j 组分别都对答案做出贡献,所有最后的答案要除2。
  • 方法二(容斥原理<pair二元组>):具体参考该篇博客,其实该博客原理和上述的思维方法无异,毕竟每个元组只会出现一次,即mp[p[a[i],b[i]]] == 1。

代码实现:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {
    
    {
    
    1, 0}, {
    
    -1, 0}, {
    
    0, 1}, {
    
    0, -1}};
using namespace std;
const int  inf = 0x7fffffff;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9 + 7;
const int  N = 2e5 + 5;

int t, A, B, k, ans;
int a[N], b[N], ca[N], cb[N];

signed main()
{
    
    
    IOS;

    cin >> t;
    while(t --){
    
    
        cin >> A >> B >> k;
        me(ca); me(cb);
        for(int i = 1; i <= k; i ++){
    
    
            cin >> a[i];
            ca[a[i]] ++;
        }
        for(int i = 1; i <= k; i ++){
    
    
            cin >> b[i];
            cb[b[i]] ++;
        }
        ans = 0;
        for(int i = 1; i <= k; i ++)
            ans += k-ca[a[i]]-cb[b[i]]+1;
        cout << ans/2 << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Satur9/article/details/113556370