Original link:
http://www.cnblogs.com/CJLHY/p/10874005.html
Did not play yesterday seemed to lose crazy, it seems that sb problem ah.
We first consider a single interval [L, R], for [L, R] in a number of x, we only need to go before it is discharged just like the number of digits after the ordering.
So overall for x, only smaller than x number of x contribute, we just calculate all smaller than its numbers, the number in front of x discharged in all segments containing x.
This can be used to maintain an array of arrays.
#include<bits/stdc++.h> #define LL long long #define LD long double #define ull unsigned long long #define fi first #define se second #define mk make_pair #define PLL pair<LL, LL> #define PLI pair<LL, int> #define PII pair<int, int> #define SZ(x) ((int)x.size()) #define ALL(x) (x).begin(), (x).end() #define fio ios::sync_with_stdio(false); cin.tie(0); using namespace std; const int N = 5e5 + 7; const int inf = 0x3f3f3f3f; const LL INF = 0x3f3f3f3f3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; const double PI = acos(-1); template<class T, class S> inline void add(T& a, S b) {a += b; if(a >= mod) a -= mod;} template<class T, class S> inline void sub(T& a, S b) {a -= b; if(a < 0) a += mod;} template<class T, class S> inline bool chkmax(T& a, S b) {return a < b ? a = b, true : false;} template<class T, class S> inline bool chkmin(T& a, S b) {return a > b ? a = b, true : false;} struct Bit { int a[N]; void modify(int x, int v) { for(int i = x; i < N; i += i & -i) add(a[i], v); } int sum(int x) { LL ans = 0; for(int i = x; i; i -= i & -i) add(ans, a[i]); return ans; } int query(int L, int R) { if(L > R) return 0; return (sum(R) - sum(L - 1) + mod) % mod; } } bit[2]; int n, a[N], id[N]; LL cnt[N]; bool cmp(int x, int y) { return a[x] < a[y]; } int main() { scanf("%d", &n); for(int i = 1; i <= n; i++) scanf("%d", &a[i]), id[i] = i; sort(id + 1, id + 1 + n, cmp); int ans = 0; for(int i = 1; i <= n; i++) { int x = id[i]; LL cnt = 0; add(cnt, 1LL * bit[0].query(1, x - 1) * (n - x + 1) % mod); add(cnt, 1LL * bit[1].query(x + 1, n) * x % mod); add(cnt, 1LL * x * (n - x + 1) % mod); add(ans, cnt * a[x] % mod); bit[0].modify(x, x); bit[1].modify(x, n - x + 1); } printf("%d\n", ans); return 0; } /* */
Reproduced in: https: //www.cnblogs.com/CJLHY/p/10874005.html