传送门
题目描述
分析
在一条链中,可以观察出结论:联通块数 = 点数 - 边数
所以我们需要求出每个点的贡献以及每一条边的贡献
首先,每一个点只有在 a[i] >= l && a[i] <= r 的时候才会被选择,所以每一个点的贡献应该是 a[i] * (n - a[i] + 1)
然后每一条边的贡献,只有当两个节点同时在这个范围内,这条边才会被算进去,所以贡献应该是:min(a[i],a[i - 1]) * (n - max(a[i],a[i - 1]) + 1)
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
ll a[N];
ll n;
int main(){
scanf("%lld",&n);
ll ans = 0;
for(int i = 1;i <= n;i++) {
scanf("%lld",&a[i]);
ans += a[i] * (n - a[i] + 1);
}
for(int i = 1;i < n;i++){
ans -= min(a[i],a[i + 1]) * (n - max(a[i],a[i + 1]) + 1);
}
printf("%lld\n",ans);
return 0;
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/