大意:给定n元素序列$a$, $1le a_i le n$, 定义函数$f(l,r)$表示范围在$[l,r]$以内的数构成的连通块个数, 求$sumlimits_{i=1}^{n}sumlimits_{j=i}^{n}f(i,j)$
对于序列$a$中一个区间$[l,r]$, 假设最小值$mi$, 最大值$ma$, 它要想构成一个连通块的充要条件是$a[l-1],a[r+1]$不在$[mi,ma]$范围内, 可以得到贡献为$mi(n-ma+1)$. 但是显然不能暴力枚举所有区间, 我们可以枚举合法区间的右端点来计算.
#include <iostream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl ' ' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head const int N = 1e6+10; int n, m, k, t; int a[N]; int main() { scanf("%d", &n); REP(i,1,n) scanf("%d", a+i); ll ans = (ll)a[n]*(n-a[n]+1); REP(i,1,n-1) { if (a[i]<a[i+1]) ans+=(ll)a[i]*(a[i+1]-a[i]); else ans+=(ll)(a[i]-a[i+1])*(n-a[i]+1); } printf("%lld ", ans); }