前置知识
题目大意
题目传送门 找满足以下条件的三元组 :
- , , 中恰好包含两个不同的值。
题目分析
既然如此,那么三元组只有以下两种形式:
彳亍,那我们把 的暴力打一遍:
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
const int N = 1e6+10, M = 1e8 + 10;
int n;
int a[N];
int ans=0;
signed main()
{
fst
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
for(int k=j+1;k<=n;k++){
if((a[i]==a[j]&&a[j]!=a[k])||(a[i]==a[k]&&a[j]!=a[k])||(a[j]==a[k]&&a[i]!=a[k])){
ans++;
}
}
}
}
cout<<ans;
return 0;
}不出意外就 T 飞了, 想办法优化一下。
我们通过观察瞪眼法发现,满足条件的三元组只涉及两个不同的数值,于是:
- 统计每个数值出现的频率。
- 枚举所有可能的数对 。
- 对于每个数对,计算它们能组成的三元组数量。
Why?
因为对于一对不同的数值 ,它们能组成的三元组只有两种:
- ,数量为
- ,数量为
其中 分别表示数值 的出现次数。
实现一下:
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
const int N = 1e6+10, M = 1e8 + 10;
int n;
int a[N];
map<int,int>mp;
vector<int>cnt;
int ans=0;
signed main()
{
fst
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
mp[a[i]]++;// 统计数字出现的次数
}
for(auto e:mp){// 收集一下
cnt.push_back(e.second);
}
int m=cnt.size();
for(int i=0;i<m;i++){// 枚举所有数对
for(int j=i+1;j<m;j++){
ans+=(cnt[i]*(cnt[i]-1)/2)*cnt[j];// (x,x,y)
ans+=(cnt[j]*(cnt[j]-1)/2)*cnt[i];// (x,y,y)
}
}
cout<<ans;
return 0;
}时间复杂度接近 ,不出意外又 T 飞了。 没办法了,我们没法直接通过枚举数对来得到答案。 只能数学推导了: 对于每个数值 ,考虑它在两种方式中的贡献:
- 当 出现两次,即 : 贡献为:
- 当 出现一次,即 : 贡献为:
令 ,则上式等于 。 综上所述,答案为:
但是,这样会重复计数每个三元组(既被 数到又被 数到),所以实际答案需要除以 2:
代码实现
#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
const int N = 1e6+10, M = 1e8 + 10;
int n;
int a[N];
map<int,int>mp;
int S2=0;// S2 为所有数值的 C( 这个数字出现的次数 ,2) 之和
int ans=0;
signed main()
{
fst
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
mp[a[i]]++;// 统计每个数字出现的次数
}
for(auto e:mp){
S2+=e.second*(e.second-1)/2;// C( 这个数字出现的次数 ,2) = 这个数字出现的次数 *( 这个数字出现的次数 -1)/2
}
for(auto e:mp){
ans+=(e.second*(e.second-1)/2)*(n-e.second)/*(x,x,y)*/+e.second*(S2-e.second*(e.second-1)/2)/*(x,y,y)*/;
}
cout<<ans/2;// 记得除以 2
return 0;
}本文的 AI 使用说明
本文仅在写作完成后使用了 Deepseek 进行了 LaTex 和 Markdown 的检查及规范。 管理大大辛苦了【送花】!