Codeforces 903D Almost Difference

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

Let's denote a function

You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

Input

The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a.

The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — elements of the array.

Output

Print one integer — the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n.

Examples
Input
5
1 2 3 1 3
Output
4
Input
4
6 6 5 5
Output
0
Input
4
6 6 4 4
Output
-8
Note

In the first example:

  1. d(a1, a2) = 0;
  2. d(a1, a3) = 2;
  3. d(a1, a4) = 0;
  4. d(a1, a5) = 2;
  5. d(a2, a3) = 0;
  6. d(a2, a4) = 0;
  7. d(a2, a5) = 0;
  8. d(a3, a4) =  - 2;
  9. d(a3, a5) = 0;
  10. d(a4, a5) = 2.

分析:刚拿到这题,先想到的是:归并排序,仔细构思了一下感觉细节很多,不大好写;转而去想线段树(归并排序能解决的线段树都行),绝对值差在1及以内的直接不考虑就行了,那么对于一个值x,要考虑的区间范围是[1,x-2]U[x+2,+inf],这样先离散化,然后线段树维护离散化后的下标,维护的信息有两个:区间和与区间计数(sum和cnt),因为对于x的查询结果sum和cnt,ans=cnt*x-sum,然后就是基本的单点更新,区间查询了。这道题要用高精度,我偷懒没写。主要原因是这道题其实用不着线段树,只要set或者map维护一下集合,然后维护前缀和即可。。这样写主程序代码长度不超过50行,比我100行的线段树代码清爽多了。

代码

最新文章

  1. Chrome firefox ie等浏览器空格 宽度不一样怎么办
  2. [liusy.api-SMJ]-创建工程范例 MAVEN archetype 学习阶段(一)
  3. 4、Python:strip(),split()
  4. 【日常小问题】windows系统操作技巧
  5. C#:Func的同步、异步调用
  6. sqlite锁的机制
  7. MySQL中无GROUP BY直接HAVING的问题【转】
  8. Divide Two Integers leetcode
  9. [Hibernate] - EAGER and LAZY
  10. Java String.contains()方法(转载)
  11. .pb.h:9:42: fatal error: google/protobuf/stubs/common.h: No such file or directory
  12. CALayer简介
  13. 音视频编解码技术(二):AAC 音频编码技术
  14. Java线程状态转换
  15. 对象名 'dbo.__MigrationHistory' 无效 错误解决
  16. win7 蓝屏信息获取和处理
  17. synchronized的一些记录
  18. Ubuntu fcitx CPU占用率很高解决方法
  19. 如何添加ECSHOP广告位置
  20. ny16 矩形嵌套

热门文章

  1. linux定时器crontab
  2. Android系统拍照之后回显并且获取文件路径
  3. 添加用户useradd,给用户设置修改密码passwd,修改用户信息usermod,修改用户密码状态chage,删除用户userdel,查询用户及组id,切换用户su,查看当前环境变量env
  4. 解决vue.js修改数据无法触发视图
  5. iOS 工程默认只允许竖屏,在单独界面进行横竖转换,屏幕旋转
  6. ecshop中的$user对象
  7. 一、源代码-面向CLR的编译器-托管模块-(元数据&IL代码)
  8. vivado hls(1)
  9. python logging一个通用的使用模板
  10. unity图片后期处理