[ABC252D] Distinct Trio 题解

[ABC252D] Distinct Trio Solution

更好的阅读体验戳此进入

题面

给定序列 $ a_n $,求满足以下条件的三元组 $ (i, j, k) $ 的数量:

$ 1 \le i \lt j \lt k \le n, a_i \neq a_j \neq a_k $。

Solution

首先不难想到三元组满足 $ i \lt j \lt k $,那么就可以认为是去掉这个条件然后求本质不同三元组,也就是求组合数。

然后考虑正难则反,直接求不好求,考虑先求 $ n \choose 3 $,然后考虑从中去掉不合法的方案。

显然要去掉的就是有两个数相同的组合数和有三个数相同的组合数。当然这个从容斥的角度来看三个数相同的似乎应该是加上,但是实现的时候会发现这个实际上不算是容斥。

我们实现的时候不难发现值域较小,于是想到需要建桶。枚举每个桶,令 $ i $ 的个数为 $ cnt_i $,如果 $ cnt_i \ge 2 $,那么直接减掉 $ {cnt_i \choose 2} \times (n - cnt_i) $,这个式子很显然,并且这个是有且仅有两个数相同的方案数,所以不需要容斥,再次枚举,如果 $ cnt_i \ge 3 $ 再减去 $ cnt_i \choose 3 $ 即可。

Code

#define _USE_MATH_DEFINES
#include <bits/stdc++.h>

#define PI M_PI
#define E M_E
#define npt nullptr
#define SON i->to
#define OPNEW void* operator new(size_t)
#define ROPNEW(arr) void* Edge::operator new(size_t){static Edge* P = arr; return P++;}

using namespace std;

mt19937 rnd(random_device{}());
int rndd(int l, int r){return rnd() % (r - l + 1) + l;}
bool rnddd(int x){return rndd(1, 100) <= x;}

typedef unsigned int uint;
typedef unsigned long long unll;
typedef long long ll;
typedef long double ld;

template < typename T = int >
inline T read(void);

int N;
int a[210000];
int cnt[210000];
ll ans(0);

int main(){
    N = read();
    for(int i = 1; i <= N; ++i)cnt[a[i] = read()]++;
    ans = (ll)N * (N - 1) * (N - 2) / (3 * 2 * 1);
    for(int i = 1; i <= 201000; ++i){
        if(cnt[i] >= 2)ans -= (ll)cnt[i] * (cnt[i] - 1) / (2 * 1) * (N - cnt[i]);
        if(cnt[i] >= 3)ans -= (ll)cnt[i] * (cnt[i] - 1) * (cnt[i] - 2) / (3 * 2 * 1);
    }printf("%lld\n", ans);
    fprintf(stderr, "Time: %.6lf\n", (double)clock() / CLOCKS_PER_SEC);
    return 0;
}

template < typename T >
inline T read(void){
    T ret(0);
    int flag(1);
    char c = getchar();
    while(c != '-' && !isdigit(c))c = getchar();
    if(c == '-')flag = -1, c = getchar();
    while(isdigit(c)){
        ret *= 10;
        ret += int(c - '0');
        c = getchar();
    }
    ret *= flag;
    return ret;
}

UPD

update-2022_12_03 初稿

posted @ 2023-01-07 15:29  Tsawke  阅读(30)  评论(0)    收藏  举报