题目链接
大致题意:
n
个
数
,
求
所
有
连
续
区
间
不
同
数
的
和
的
总
和
。
n个数,求所有连续区间不同数的和的总和。
n个数,求所有连续区间不同数的和的总和。
解题报告:
考虑不包含重复数
−
>
->
−> 对当前位置而言,它的贡献为
a
[
x
]
∗
i
∗
(
n
−
i
+
1
)
:
即
该
位
置
在
所
有
包
含
它
的
连
续
区
间
的
贡
献
a[x] *i* (n-i+1):即该位置在所有包含它的连续区间的贡献
a[x]∗i∗(n−i+1):即该位置在所有包含它的连续区间的贡献。
考虑重复数
−
>
->
−>
p
o
s
[
i
]
pos[i]
pos[i] 表示
i
i
i 这个数上一次出现的位置,初始化时为
0
0
0
同样的方法思考:因为相同的数仅被统计一次,那么所有出现重复数的连续区间都会因上次的出现已经被统计了,我们只需要从上次出现的下一位置开始做贡献
a
[
i
]
∗
(
i
−
p
o
s
[
a
[
i
]
]
)
∗
(
n
−
i
+
1
)
a[i]*(i-pos[a[i]])*(n-i+1)
a[i]∗(i−pos[a[i]])∗(n−i+1) 即可
代码展示:
#include<bits/stdc++.h>
#define LL long long
#define pii pair<int,int>
#define all(x) x.begin(),x.end()
#define mem(a, b) memset(a,b,sizeof(a))
using namespace std;
const int maxn = 1e6 + 5;
const int MOD = 1e9 + 7;
inline int read() {
int s = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();}
while (ch >= '0' && ch <= '9') {s = (s << 1) + (s << 3) + ch - '0'; ch = getchar();}
return s * f;
}
inline void write(LL x) {
if (x < 0) x = -x, putchar('-');
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
}
int a[maxn], pos[maxn];
LL sum[maxn];
int main() {
int T = read(), n;
while (T--) {
mem(pos,0);
n=read();
LL ans=0;
for(int i=1;i<=n;i++) a[i]=read();
for(int i=1;i<=n;i++) {
ans+=1LL*(i-pos[a[i]])*(n-i+1)*a[i];
pos[a[i]]=i;
}
write(ans);
putchar('\n');
}
return 0;
}