码迷,mamicode.com
首页 > 其他好文 > 详细

CodeForces-1151E-Number of Components

时间:2019-04-22 20:57:58      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:print   contains   cti   codeforce   lin   without   nts   can   and   

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;
}

CodeForces-1151E-Number of Components

标签:print   contains   cti   codeforce   lin   without   nts   can   and   

原文地址:https://www.cnblogs.com/hitgxz/p/10752634.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!