D - Distinct Trio - AtCoder Beginner Contest 252
D - Distinct Trio
本题有三种思路:
- 逆向思维,用不加限制的排列数-不符合条件的;
- 将题目转化为求\(A_{i}<A_{j}<A_{k}\)的个数。
- 顺序递推
这篇文章详解了第一种,那我就来说清楚第二种。
原题目为,给定序列
\[\text{}A= (A_1, A_2, ..., A_n)
,求满足
1 \leq i<j<k \leq N 且A_{i}\not = A_{j} \not = A_{k}的(i, j, k) 的数量
\]
官方题解
\[\text { The condition can be rephrased as follows: find the number of triplets }(i, j, k) \text { such that } A_{i}<A_{j}<A_{k}\\
\]
\[\text { Details:For a triplet }(i, j, k) \text { satisfying the original condition, there exists a unique permutation of } i, j, k \text { such that } A_{i}<A_{j}<A_{k}\\ \text { Conversely, for a triplet }(i, j, k) \text { such that } A_{i}< A_{j}<A_{k} \text {, there exists a unique permutation of } i, j, k \text { such that } i<j<k \text {. }
\]
证明
不妨记
\[满足
1 \leq i<j<k \leq N 且A_{i}\not = A_{j} \not = A_{k}的(i, j, k)代表的集合为S_1,\\
满足 A_{i}<A_{j}<A_{k}的(i, j, k)代表的集合为S_2 \\
count(S_i)表示集合S_i的元素个数
\]
我们要证两个集合的元素个数相等
只要证明
\[\begin{cases}
count(S_1) \le count(S_2) &&{(1)} \\
count(S_2) \ge count(S1) &&{(2)}
\end{cases}
\]
即证明左边任意元素可以转换到右边,右边可以转换到左边即可。
先证(1)式。
假设存在一组数对满足\(S_1\),那么\(i, j, k\)必然不相等,此时\(A_i, A_j, A_k\)不一定依次增大,但我们总可以通过调整三者顺序的方式,使得\(A_{i'} < A_{j'} <A_{k'}\)。
\(S_1\)中任意一组数对,都可以进行这样的转换,故(1)式成立。
再证(2)式。
方法类似,假设存在一组数对满足\(S_2\),因为\(A_{i}<A_{j}<A_{k}\),故\(A_{i}\not = A_{j} \not = A_{k}\),那么\(i, j, k\)必然不相等,可以通过调整顺序,可以使得\(i< j < k\)。
\(S_2\)中任意一组数对,都可以进行这样的转换,故(2)式成立。
再证(2)式。
综上,两个集合元素个数相等。
第三种
第三种还不太理解,贴个代码
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<cmath>
#include<set>
#include<cstring>
#include<vector>
#include<map>
#define endl '\n'
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
int a[N];
int cnt[N];
int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)cin >> a[i];
	LL ans = 0;
	LL sum = 0;
	int dif = 0;
	int s = 0;
	for (int i = 0; i < n; i++) {
		if (cnt[a[i]] == 0) dif++;
		if (dif == 2) sum = 1;
		if (dif > 2) ans += sum-(s-cnt[a[i]])*cnt[a[i]];
		//cout << ans<<" "<<sum <<" "<< s << endl;
		if (dif > 2) sum += s - cnt[a[i]];
		cnt[a[i]]++;
		s++;
	}
	cout << ans;
	return 0;
}
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号