#include<cstdio>
#include<stack>
#include<ctime>
#include<cstdlib>
#define MX 500006
#define LL long long
using namespace std;
int N,nxt[MX],cm[MX],ar[MX],nx[MX];
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&N);
for(int i=0;i<N;i++) scanf("%d",&ar[i]);
stack<int> S,G;
for(int i=0;i<N;i++){
while(!S.empty() && ar[S.top()]<ar[i]) nxt[S.top()]=i,S.pop();
S.push(i);
}
while(!S.empty()) nxt[S.top()]=-1,S.pop();
for(int i=0;i<N;i++){
while(!G.empty() && ar[G.top()]<=ar[i]) nx[G.top()]=i,G.pop();
G.push(i);
}
while(!G.empty()) nx[G.top()]=-1,G.pop();
LL ans=0;
for(int i=N-1;i>=0;i--){
if(nxt[i]==-1) ans+=(N-i-1);
else ans+=(nxt[i]-i-1)+cm[nxt[i]];
if(nx[i]==-1) cm[i]=1;
else cm[i]=cm[nx[i]]+1;
}
printf("%lld\n",ans);
/*LL ch=0;
for(int i=0;i<N;i++){
int mx=ar[i];
for(int j=i+1;j<N;j++){
mx=max(mx,ar[j]);
if(mx<=max(ar[i],ar[j])) ++ch;
}
}
printf("%lld\n",ch);*/
}
return 0;
}
I2luY2x1ZGU8Y3N0ZGlvPgojaW5jbHVkZTxzdGFjaz4KI2luY2x1ZGU8Y3RpbWU+CiNpbmNsdWRlPGNzdGRsaWI+CiNkZWZpbmUgTVggNTAwMDA2CiNkZWZpbmUgTEwgbG9uZyBsb25nCnVzaW5nIG5hbWVzcGFjZSBzdGQ7CmludCBOLG54dFtNWF0sY21bTVhdLGFyW01YXSxueFtNWF07CgppbnQgbWFpbigpewogICAgaW50IFQ7CiAgICBzY2FuZigiJWQiLCZUKTsKICAgIHdoaWxlKFQtLSl7CiAgICAgICAgc2NhbmYoIiVkIiwmTik7CiAgICAgICAgZm9yKGludCBpPTA7aTxOO2krKykgc2NhbmYoIiVkIiwmYXJbaV0pOwogICAgICAgIHN0YWNrPGludD4gUyxHOwogICAgICAgIGZvcihpbnQgaT0wO2k8TjtpKyspewogICAgICAgICAgICB3aGlsZSghUy5lbXB0eSgpICYmIGFyW1MudG9wKCldPGFyW2ldKSBueHRbUy50b3AoKV09aSxTLnBvcCgpOwogICAgICAgICAgICBTLnB1c2goaSk7CiAgICAgICAgfQogICAgICAgIHdoaWxlKCFTLmVtcHR5KCkpIG54dFtTLnRvcCgpXT0tMSxTLnBvcCgpOwogICAgICAgIGZvcihpbnQgaT0wO2k8TjtpKyspewogICAgICAgICAgICB3aGlsZSghRy5lbXB0eSgpICYmIGFyW0cudG9wKCldPD1hcltpXSkgbnhbRy50b3AoKV09aSxHLnBvcCgpOwogICAgICAgICAgICBHLnB1c2goaSk7CiAgICAgICAgfQogICAgICAgIHdoaWxlKCFHLmVtcHR5KCkpIG54W0cudG9wKCldPS0xLEcucG9wKCk7CiAgICAgICAgTEwgYW5zPTA7CiAgICAgICAgZm9yKGludCBpPU4tMTtpPj0wO2ktLSl7CiAgICAgICAgICAgIGlmKG54dFtpXT09LTEpIGFucys9KE4taS0xKTsKICAgICAgICAgICAgZWxzZSBhbnMrPShueHRbaV0taS0xKStjbVtueHRbaV1dOwogICAgICAgICAgICBpZihueFtpXT09LTEpIGNtW2ldPTE7CiAgICAgICAgICAgIGVsc2UgY21baV09Y21bbnhbaV1dKzE7CiAgICAgICAgfQogICAgICAgIHByaW50ZigiJWxsZFxuIixhbnMpOwogICAgICAgIC8qTEwgY2g9MDsKICAgICAgICBmb3IoaW50IGk9MDtpPE47aSsrKXsKICAgICAgICAgICAgaW50IG14PWFyW2ldOwogICAgICAgICAgICBmb3IoaW50IGo9aSsxO2o8TjtqKyspewogICAgICAgICAgICAgICAgbXg9bWF4KG14LGFyW2pdKTsKICAgICAgICAgICAgICAgIGlmKG14PD1tYXgoYXJbaV0sYXJbal0pKSArK2NoOwogICAgICAgICAgICB9CiAgICAgICAgfQogICAgICAgIHByaW50ZigiJWxsZFxuIixjaCk7Ki8KICAgIH0KICAgIHJldHVybiAwOwp9Cg==