CodeForces-1151E-Number of Components

Description

The Kingdom of Kremland is a tree (a connected undirected graph without cycles) consisting of \(n\) vertices. Each vertex \(i\) has its own value \(a_i\). All vertices are connected in series by edges. Formally, for every \(1 \le i \lt n\) there is an edge between the vertices of \(i\) and \(i+1\).

Denote the function \(f(l,r)\), which takes two integers \(l\) and \(r\) \((l \le r)\):

  • We leave in the tree only vertices whose values range from \(l\) to \(r\).

  • The value of the function will be the number of connected components in the new graph.

Your task is to calculate the following sum:
\[ \sum_{l=1}^{n}\sum_{r=l}^{n}f(l,r) \]

Input

The first line contains a single integer \(n(1≤n≤10^5)\) — the number of vertices in the tree.

The second line contains \(n\) integers \(a_1,a_2,\dots,a_n\) (\(1 \le a_i \le n\)) — the values of the vertices.

Output

Print one number — the answer to the problem.

Examples

Input

3
2 1 3

Output

7

Input

4
2 1 1 3

Output

11

Input

10
1 5 2 5 5 3 10 6 5 1

Output

104

Solution

这种题显然是求贡献,\(n\)个点构成一条链,所以每个分量都是一个区间,考虑所有左端点为\(a[i]\)的区间对答案的贡献,若\(a[i - 1] < a[i]\),那么对于满足\(a[i-1] \lt l \le a[i], a[i] \le r \le n\)的所有\((l, r)\),得到的区间中都会有一个左端点为\(a[i]\)的,所以对答案的贡献是\((a[i] - a[i - 1]) * (n - a[i] + 1)\)

\(a[i-1] > a[i]\),那么对于满足\(1 \le l \le a[i], a[i] \le r \lt a[i - 1]\)的所有\((l, r)\),得到的区间中都会有一个左端点为\(a[i]\)的,对答案的贡献是\(a[i] * (a[i - 1] - a[i])\)

同理,可以计算出所有以\(a[i]\)为右端点的区间的贡献,求和之后,得到的结果是答案的两倍,除以2之后输出即可,复杂度\(O(n)\)

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
  int n;
  scanf("%d", &n);
  vector<int> a(n + 2);
  for (int i = 1; i <= n; ++i)
    scanf("%d", &a[i]);
  a[0] = a[n + 1] = 0;
  ll ans = 0;
  for (int i = 1; i <= n; ++i) {
    if (a[i - 1] < a[i]) {
      ans += (ll)(a[i] - a[i - 1]) * (n - a[i] + 1);
    } else {
      ans += (ll)(a[i - 1] - a[i]) * a[i];
    }
    if (a[i + 1] < a[i]) {
      ans += (ll)(a[i] - a[i + 1]) * (n - a[i] + 1);
    } else {
      ans += (ll)(a[i + 1] - a[i]) * a[i];
    }
  }
  printf("%I64d\n", ans / 2);
  return 0;
}

转载于:https://www.cnblogs.com/hitgxz/p/10752634.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值