TLE 求助
查看原帖
TLE 求助
685964
shuqiang楼主2025/1/18 01:40
#include<iostream>
#include<algorithm>
#include<set>

using namespace std;
typedef long long ll;

const int N = 1e6 + 10;
int n, a[N]; ll s1, s2;

int read_int(){
    int x = 0; char ch = ' '; while(!isdigit(ch)) ch = getchar();
    while(isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();} return x;
}

struct pii{
	int x, y;
	
	bool operator < (const pii & o) const{
		return x < o.x;
	}
} b[N];

set<int> st1, st2;

int main(){
	n = read_int();
	for(int i = 1; i <= n; i++){
		a[i] = read_int();
		b[i].x = a[i], b[i].y = i;
	} 
	sort(b + 1, b + 1 + n);
	for(int i = 1; i <= n; i++){
		int l, r;
		auto it = st1.upper_bound(b[i].y);
		if(it == st1.end()) r = n;
		else r = *it - 1;
		if(it == st1.begin()) l = 1;
		else{
			it--;
			l = *it + 1;
		}
		s1 += (ll)(r - b[i].y + 1) * (b[i].y - l + 1) * b[i].x;
		st1.insert(b[i].y);
	}
	for(int i = n; i >= 1; i--){
		int l, r;
		auto it = st2.upper_bound(b[i].y);
		if(it == st2.end()) r = n;
		else r = *it - 1;
		if(it == st2.begin()) l = 1;
		else{
			it--;
			l = *it + 1;
		}
		s2 += (ll)(r - b[i].y + 1) * (b[i].y - l + 1) * b[i].x;
		st2.insert(b[i].y);
	}
	cout << s2 - s1;
	return 0;
}

2025/1/18 01:40
加载中...