CodeForces-1151E-Number of Components

Posted hitgxz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
", ans / 2);
  return 0;
}

以上是关于CodeForces-1151E-Number of Components的主要内容,如果未能解决你的问题,请参考以下文章

7*7矩阵求逆的verilog实现

滚动数组要来回赋初值呀。。orzzzzzzzzzzzzzzzzzzzzzzzzzz

排序总结C++

常见算法

算法 -- o, o(n), o(logn), o(nlogn)

o, o(n), o(logn), o(nlogn)