#ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; typedef long long int64; typedef unsigned long long uint64; #define two(X) (1<<(X)) #define twoL(X) (((int64)(1))<<(X)) #define contain(S,X) (((S)&two(X))!=0) #define containL(S,X) (((S)&twoL(X))!=0) const double pi=acos(-1.0); const double eps=1e-11; template inline void ckmin(T &a,T b){if(b inline void ckmax(T &a,T b){if(b>a) a=b;} template inline T sqr(T x){return x*x;} typedef pair ipair; #define SIZE(A) ((int)A.size()) #define LENGTH(A) ((int)A.length()) #define MP(A,B) make_pair(A,B) #define PB(X) push_back(X) #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,a) for(int i=0;i<(a);++i) #define ALL(A) A.begin(),A.end() const int maxn=(2<<20); const int MOD=1000000007; #define MUL(a,b) ((int)((int64)(a)*(b)%(MOD))) inline int ADD(int a,int b) { a+=b; if (a>=MOD) a-=MOD; return a; } inline int SUB(int a,int b) { a-=b; if (a<0) a+=MOD; return a; } inline void ADDTO(int& a,int b) { a+=b; if (a>=MOD) a-=MOD; } inline void SUBTO(int& a,int b) { a-=b; if (a<0) a+=MOD; } const int INV_2=(MOD+1)/2; int n; int a[maxn]; int p[maxn]; int c2[maxn]; int sc2[maxn]; int sc3[maxn]; int b[maxn]; int father[maxn]; int cnt[maxn]; void prepare() { REP(i,maxn) c2[i]=MUL(MUL(i,i-1),INV_2); sc2[0]=c2[0]; FOR(i,1,maxn) sc2[i]=ADD(sc2[i-1],c2[i]); sc3[0]=c2[0]; sc3[1]=c2[1]; FOR(i,2,maxn) sc3[i]=ADD(sc3[i-2],c2[i]); } int get_father(int p) { int r=p; for (;father[r]>=0;r=father[r]); for (int t=father[p];t>=0;t=father[p]) father[p]=r,p=t; return r; } int eval(int p) { if (p==0 || p+cnt[p]-1==n-1) return 0; return sc2[cnt[p]+1]; } int eval0() { int l1=(b[0]?cnt[get_father(0)]:0); int l2=(b[n-1]?cnt[get_father(n-1)]:0); int r=c2[l1+1]; int m=min(l2,l1-1); if (m>=1) { int m2=l1+l2; int m1=l1+l2+2-m*2; ADDTO(r,sc3[m2]); if (m1-2>=0) SUBTO(r,sc3[m1-2]); } /* for (int k=1;k<=m;k++) { int e=l2-k+1+l1-k+1; ADDTO(r,c2[e]); } */ m=max(1,m+1); if (mb) swap(a,b); int r1=ADD(eval(a),eval(b)); father[b]=a; cnt[a]+=cnt[b]; int r2=eval(a); return SUB(r2,r1); } vector ss(vector a) { vector r; int n=SIZE(a); FOR(i,1,n+1) REP(j,n-i+1) { int c=a[j]; FOR(k,j,j+i) ckmax(c,a[k]); r.push_back(c); } return r; } int main() { #ifdef _MSC_VER freopen("input.txt","r",stdin); #endif std::ios::sync_with_stdio(false); prepare(); cin>>n; REP(i,n) cin>>a[i]; /* n=10; REP(i,n) a[i]=rand()%5; REP(i,n) printf("%d ",a[i]); printf("\n"); int ret2=0; vector bb=ss(ss(vector(a,a+n))); for (int p:bb) ret2+=p; printf("%d\n",ret2); */ REP(i,n) p[i]=i; sort(p,p+n,[](int x,int y) { return a[x]=0 && b[k-1]) ADDTO(delta,merge_f(k,k-1)); if (k+1