博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
求一个序列所有区间(区间内不同数的个数)的和
阅读量:4332 次
发布时间:2019-06-06

本文共 1585 字,大约阅读时间需要 5 分钟。

求一个序列所有区间(区间内不同数的个数)的和

链接:

来源:牛客网

Gromah and LZR have entered the second level. There is a sequence a1,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 ≤ \(a_i\) ≤ n ≤ \(10^5\)

输出描述:

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] are all 1.
The beauty values of subintervals [1,2],[1,3],[2,3],[3,4] are all 2.
The beauty values of subintervals [1,4],[2,4] are all 3.
As a result, the sum of all beauty values are 1×4+2×4+3×2=18

题意

求一个序列所有区间(区间内不同数的个数)的和

题解

递推,记录\(a_i\)出现的位置,如果\(a_i\)以前出现的位置是cnt[\(a_i\)],那么区间[L, i]和[L, i-1](0<L<=cnt[\(a_i\)])的结果是一样的,[L, i]比[L,i-1](cnt[\(a_i\)] < L <= i)多1,因为在这些区间,\(a_i\)属于不同的数。

#include 
int cnt[100010];int main() { int n, a; scanf("%d", &n); long long sum[100010], ans = 0; sum[0] = 0; for(int i = 1; i <= n; i++) { scanf("%d", &a); sum[i] = sum[i-1] + (i - cnt[a]); cnt[a] = i; ans += sum[i]; } printf("%lld\n", ans); return 0;}

转载于:https://www.cnblogs.com/fanshhh/p/11333158.html

你可能感兴趣的文章
Leetcode 6——ZigZag Conversion
查看>>
dockerfile_nginx+PHP+mongo数据库_完美搭建
查看>>
Http协议的学习
查看>>
【转】轻松记住大端小端的含义(附对大端和小端的解释)
查看>>
设计模式那点事读书笔记(3)----建造者模式
查看>>
ActiveMQ学习笔记(1)----初识ActiveMQ
查看>>
Java与算法之(2) - 快速排序
查看>>
Windows之IOCP
查看>>
机器学习降维之主成分分析
查看>>
CTP2交易所成交回报
查看>>
WebSocket & websockets
查看>>
openssl 升级
查看>>
ASP.NET MVC:通过 FileResult 向 浏览器 发送文件
查看>>
CVE-2010-2883Adobe Reader和Acrobat CoolType.dll栈缓冲区溢出漏洞分析
查看>>
使用正确的姿势跨域
查看>>
AccountManager教程
查看>>
Android学习笔记(十一)——从意图返回结果
查看>>
算法导论笔记(四)算法分析常用符号
查看>>
ultraedit激活
查看>>
总结(6)--- python基础知识点小结(细全)
查看>>