链接:https://ac.nowcoder.com/acm/contest/888/B
来源:牛客网
题目描述
Gromah and LZR have entered the second level. There is a sequence a1,a2,⋯ ,ana_1, a_2, \cdots, a_na1,a2,⋯,an on the wall.
There is also a note board saying "the beauty value of a sequence is the number of different elements in the sequence".
LZR soon comes up with the password of this level, which is the sum of the beauty values of all successive subintervals of the sequence on the wall.
Please help them determine the password!
输入描述:
The first line contains one positive integer nn_{}n, denoting the length of the sequence.
The second line contains nn_{}n positive integers a1,a2,⋯ ,ana_1, a_2, \cdots, a_na1,a2,⋯,an, denoting the sequence.
1≤ai≤n≤1051 \le a_i \le n \le 10^51≤ai≤n≤105
输出描述:
Print a non-negative integer in a single line, denoting the answer.
示例1
输入
复制
4 1 2 1 3
输出
复制
18
说明
The beauty values of subintervals [1,1],[2,2],[3,3],[4,4][1,1], [2,2], [3,3], [4,4]_{}[1,1],[2,2],[3,3],[4,4] are all 11_{}1. The beauty values of subintervals [1,2],[1,3],[2,3],[3,4][1,2], [1,3], [2,3], [3,4]_{}[1,2],[1,3],[2,3],[3,4] are all 22_{}2. The beauty values of subintervals [1,4],[2,4][1,4], [2,4]_{}[1,4],[2,4] are all 33_{}3. As a result, the sum of all beauty values are 1×4+2×4+3×2=181\times 4 + 2\times 4 + 3\times 2 = 181×4+2×4+3×2=18.
求每个子区间不同数的数目之和
思路:与这道题相同https://blog.csdn.net/qq_42936517/article/details/84620256
思路:找每个数对最终结果的贡献
包含a[i]的连续子序列有:
1.如果a[i]之前没出现过,就有(n-i)(i+1)个
2.如果a[i]之前出现过了,就有(n-i)((i+1)-(vis[a[i]]+1))个
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+5;
ll a[N];
int vis[N];
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
memset(vis,-1,sizeof(vis));
ll ans=0;
for(int i=0;i<n;i++){
if(vis[a[i]]!=-1){
ans+=(ll)(n-i)*(i-vis[a[i]]);
}
else{
ans+=(ll)(n-i)*(i+1);
}
vis[a[i]]=i;
}
printf("%lld\n",ans);
return 0;
}