[ABC318E]Sandwiches 题解

题意

给定一个序列 \(A\),要求找有多少个三元组 \((i,j,k)\) 满足以下条件:

  • \(1\le i < j< k \le N\)
  • \(A_i=A_k\)
  • \(A_i \ne A_j\)

思路

相当于是找每两个相同的元素中有多少个不同的数字。

例如:

1 2 1 3 1

答案显然是 4,即是\((1,2,3)(1,2,5)(1,4,5)(3,4,5)\)

\(q[A[i]]\) 表示在 \(i\) 这个下标之前的数中最后出现与 \(A_i\) 相同的数的下标。

那么像上例的 \((1,2,3)\) 的贡献即是 \(i-q[A[i]]-1\)

但是显然不可能这么简单,可以发现每扫到一个数,前面的数也有相应的贡献。

不妨用 \(gx[i]\) 表示第 \(i\) 个数的贡献。

再设 \(apper[A[i]]\) 为到 \(i\) 这个下标时前面的数中出现了多少次 \(A_i\)

推一下式子,很容易得到:

\[gx[i]=(i-q[A[i]]-1)*apper[A[i]]+gx[q[a[i]] \]

最后扫一遍加入答案即可.

代码

#include<bits/stdc++.h>
#define int long long
#define endl "\n"
using namespace std;
template<typename P>
inline void read(P &x){
   	P res=0,f=1;
   	char ch=getchar();
   	while(ch<'0' || ch>'9'){
   		if(ch=='-') f=-1;
   		ch=getchar();
   	}
   	while(ch>='0' && ch<='9'){
   		res=res*10+ch-'0';
   		ch=getchar();
	}
	x=res*f;
}
int n;
int a[300010];
int gx[300010];
map<int,int> q;
map<int,int> apper;
signed main(){
	read(n);
	for(int i=1;i<=n;++i){
		read(a[i]);
	}
	for(int i=1;i<=n;++i){
		if(q[a[i]]==0){
			q[a[i]]=i;
			apper[a[i]]++;
			continue;
		}
		int now=i;
		int las=q[a[i]];
		gx[i]=(now-las-1)*apper[a[i]]+gx[las];
		apper[a[i]]++;
		q[a[i]]=i;
	}
	int ans=0;
	for(int i=1;i<=n;++i) ans+=gx[i];
	cout<<ans<<endl;
	return 0;
}


posted @ 2024-07-25 14:55  God_Max_Me  阅读(12)  评论(0)    收藏  举报