#include <cstdio>
#include <vector>

#define MAXN 100005
#define SQRMAXN 700
#define INF 0x3f3f3f3f
#define pb push_back

using namespace std;

int N, M, A[MAXN], f[MAXN], nposs, poss_num[SQRMAXN];
int sums[SQRMAXN][MAXN];
char appear[SQRMAXN][MAXN];

void Test() {
	int i;

	printf ("Array :\n");
	for ( i=1; i<=N; ++i ) {
		printf ("%d\n", A[i]);
	}

	printf ("%d possible numbers :\n", nposs );
	for ( i=1; i<=nposs; ++i ) {
		printf ("%d\n", poss_num[i]);
	}

	for ( i=1; i<=N; ++i ) {
		printf ("Frequency of %d is %d\n", A[i], f[ A[i] ] );
	}
}

void Read() {
	int i;

	scanf ("%d %d", &N, &M);
	for ( i=1; i<=N; ++i ) {
		scanf ("%d", &A[i]);
	}
}

void Frequencies() {
	int i;

	for ( i=1; i<=N; ++i ) {
		if ( A[i] <= N ) {
			++f[ A[i] ];
		}
	}
}

void Possible_Nums() {
	int i;

	for ( i=1; i<=N; ++i ) {
		if ( f[i] >= i ) {
			poss_num[ ++nposs ] = i;
		}
	}
}

int Position ( int x ) {
	int lo, mid, hi;

	lo = 1;
	hi = nposs;
	while ( lo < hi ) {
		mid = (lo+hi+1) / 2;
		if ( poss_num[ mid ] <= x ) {
			lo = mid;
		}
		else {
			hi = mid-1;
		}
	}

	return lo;
}

void Appear() {
	int i, pos;

	for ( i=1; i<=N; ++i ) {
		if ( A[i] <= N && f[ A[i] ] >= A[i] ) {
			pos = Position(A[i]);
			appear[ pos ][i] = 1;
		}
	}
}

void Make_Sums() {
	int i, j;

	for ( i=1; i<=nposs; ++i ) {
		for ( j=1; j<=N; ++j ) {
			sums[i][j] = sums[i][j-1] + appear[i][j];
		}
	}

}

void Answer_Queries() {
	int i, from, to, lo, hi, ans, possible;

	for ( i=1; i<=M; ++i ) {
		scanf ("%d %d", &from, &to);
		ans = 0;

		for ( possible = 1; possible <= nposs; ++possible ) {
			if ( sums[possible][hi]-sums[possible][lo-1] == poss_num[ possible ] ) {
				++ans;
			}
		}

		printf ("%d\n", ans );
	}
}

int main ( void ) {

	Read();
	Frequencies();
	Possible_Nums();
	Appear();
	Make_Sums();
	//Test();
	Answer_Queries();

	return 0;
}


#include <cstdio>
#include <vector>

#define MAXN 100005
#define SQRMAXN 453
#define pb push_back

using namespace std;

int N, M, A[MAXN], f[MAXN], nposs, poss_num[SQRMAXN];
int sums[SQRMAXN][MAXN];
char appear[SQRMAXN][MAXN];

void Test() {
	int i;

	printf ("Array :\n");
	for ( i=1; i<=N; ++i ) {
		printf ("%d\n", A[i]);
	}

	printf ("%d possible numbers :\n", nposs );
	for ( i=1; i<=nposs; ++i ) {
		printf ("%d\n", poss_num[i]);
	}

	for ( i=1; i<=N; ++i ) {
		printf ("Frequency of %d is %d\n", A[i], f[ A[i] ] );
	}
}

void Read() {
	int i;

	scanf ("%d %d", &N, &M);
	for ( i=1; i<=N; ++i ) {
		scanf ("%d", &A[i]);
	}
}

void Frequencies() {
	int i;

	for ( i=1; i<=N; ++i ) {
		if ( A[i] <= N ) {
			++f[ A[i] ];
		}
	}
}

void Possible_Nums() {
	int i;

	for ( i=1; i<=N; ++i ) {
		if ( f[i] >= i ) {
			poss_num[ ++nposs ] = i;
		}
	}
}

int Position ( int x ) {
	int lo, mid, hi;

	lo = 1;
	hi = nposs;
	while ( lo < hi ) {
		mid = (lo+hi+1) / 2;
		if ( poss_num[ mid ] <= x ) {
			lo = mid;
		}
		else {
			hi = mid-1;
		}
	}

	return lo;
}

void Appear() {
	int i, pos;

	for ( i=1; i<=N; ++i ) {
		if ( A[i] <= N && f[ A[i] ] >= A[i] ) {
			pos = Position(A[i]);
			appear[ pos ][i] = 1;
		}
	}
}

void Make_Sums() {
	int i, j;

	for ( i=1; i<=nposs; ++i ) {
		for ( j=1; j<=N; ++j ) {
			sums[i][j] = sums[i][j-1] + appear[i][j];
		}
	}

}

void Answer_Queries() {
	int i, from, to, ans, possible;

	for ( i=1; i<=M; ++i ) {
		scanf ("%d %d", &from, &to);
		ans = 0;

		for ( possible = 1; possible <= nposs; ++possible ) {
			if ( sums[possible][to]-sums[possible][from-1] == poss_num[ possible ] ) {
				++ans;
			}
		}

		printf ("%d\n", ans );
	}
}

int main ( void ) {

	Read();
	Frequencies();
	Possible_Nums();
	Appear();
	Make_Sums();
	//Test();
	Answer_Queries();

	return (0);
}


#include <cstdio>
#include <vector>

#define MAXN 100005
#define SQRMAXN 700
#define INF 0x3f3f3f3f
#define pb push_back

using namespace std;

int N, M, A[MAXN], f[MAXN], nposs, poss_num[SQRMAXN];
vector<int> appear[SQRMAXN];

void Test() {
	int i;

	printf ("Array :\n");
	for ( i=1; i<=N; ++i ) {
		printf ("%d\n", A[i]);
	}

	printf ("%d possible numbers :\n", nposs );
	for ( i=1; i<=nposs; ++i ) {
		printf ("%d\n", poss_num[i]);
	}

	for ( i=1; i<=N; ++i ) {
		printf ("Frequency of %d is %d\n", A[i], f[ A[i] ] );
	}

	for ( i=1; i<=nposs; ++i ) {
		printf ("Appearances of %d\n", poss_num[i]);
		for ( int j=0; j<appear[i].size(); ++j ) {
			printf("%d ", appear[i][j]);
		}
		printf ("\n");
	}
}

void Read() {
	int i;

	scanf ("%d %d", &N, &M);
	for ( i=1; i<=N; ++i ) {
		scanf ("%d", &A[i]);
	}
}

void Frequencies() {
	int i;

	for ( i=1; i<=N; ++i ) {
		if ( A[i] <= N ) {
			++f[ A[i] ];
		}
	}
}

void Possible_Nums() {
	int i;

	for ( i=1; i<=N; ++i ) {
		if ( f[i] >= i ) {
			poss_num[ ++nposs ] = i;
		}
	}
}

int Position ( int x ) {
	int lo, mid, hi;

	lo = 1;
	hi = nposs;
	while ( lo < hi ) {
		mid = (lo+hi+1) / 2;
		if ( poss_num[ mid ] <= x ) {
			lo = mid;
		}
		else {
			hi = mid-1;
		}
	}

	return lo;
}

void Appear() {
	int i, pos;

	for ( i=1; i<=N; ++i ) {
		if ( A[i] <= N && f[ A[i] ] >= A[i] ) {
			pos = Position(A[i]);
			appear[ pos ].pb (i);
		}
	}
}

int Lower_Bound ( int from, int x ) {
	int lo, mid, hi;

	lo = 0;
	hi = appear[x].size()-1;
	while ( lo < hi ) {
		mid = (lo+hi) / 2;
		if ( appear[x][mid] >= from ) {
			hi = mid;
		}
		else {
			lo = mid+1;
		}
	}

	return appear[x][lo] >= from ? lo : INF;
}

int Upper_Bound ( int to, int x ) {
	int lo, mid, hi;

	lo = 0;
	hi = appear[x].size()-1;
	while ( lo < hi ) {
		mid = (lo+hi+1) / 2;
		if ( appear[x][mid] <= to ) {
			lo = mid;
		}
		else {
			hi = mid-1;
		}
	}

	return appear[x][lo] <= to ? lo : -INF;
}

void Answer_Queries() {
	int i, from, to, lo, hi, ans, possible;

	for ( i=1; i<=M; ++i ) {
		scanf ("%d %d", &from, &to);
		ans = 0;

		for ( possible = 1; possible <= nposs; ++possible ) {
			lo = Lower_Bound ( from, possible );
			hi = Upper_Bound ( to, possible );
			//printf ("Num %d, low %d, hi %d\n", poss_num[possible],lo,hi);
			if ( hi-lo+1 == poss_num[ possible ] ) {
				++ans;
			}
		}

		printf ("%d\n", ans );
	}
}

int main ( void ) {

	Read();
	Frequencies();
	Possible_Nums();
	Appear();
	//Test();
	Answer_Queries();

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

int S;

struct Query{
	int l, r, i;
	Query(){}
	Query(int l, int r, int i): l(l), r(r), i(i){}
} q[200010];

bool cmp(const Query &A, const Query &B)
{
  if ( (A.l / S) != (B.l / S) ) return (A.l / S) < (B.l / S);
  return A.r < B.r;
}

int currentL = 0;
int currentR = 0;

map<int,int> conta;

int v[100010];
int ans[100010];

int answer = 0;

void add(int position){

	conta[v[position]]++;
	if(conta[v[position]] == v[position])
		answer++;
}

void remove(int position){

		conta[v[position]]--;
		if(conta[v[position]] == v[position] -1)
		answer--;
}

int main(){

	int n, Q;
	scanf("%d %d", &n, &Q);
	for(int i = 0; i < n; i++)scanf("%d", &v[i]);

	for(int i = 0; i < Q; i++){
		scanf("%d %d", &q[i].l, &q[i].r);
		q[i].l--;
		q[i].r--;
		q[i].i = i;
	}

	S = sqrt(n);
	sort(q, q + Q, cmp);

	add(0);
	for(int i = 0; i < Q; i++){
		int L = q[i].l, R = q[i].r;

		while (currentL < L){
			remove(currentL);
			currentL++;
		}

		while(currentL > L){
			currentL--;
			add(currentL);
		}
		while (currentR <= R){
			currentR++;
			add(currentR);
		}
		while(currentR > R){
			remove(currentR);
			currentR--;
		}
		ans[q[i].i] = answer;
	}

	for(int i = 0; i < Q; i++) printf("%d\n", ans[i]);
	return 0;
}
// 1470779818046


#include <bits/stdc++.h>

using namespace std;

const int N = 100005, SQRT = 200, Q = 100005;

struct Query {
  int l, r, id;
  Query() {}
  Query(int l, int r, int id) : l(l), r(r), id(id) {}

  bool operator < (const Query& q) const {
    if (l / SQRT != q.l / SQRT) return l / SQRT < q.l / SQRT;
    return r > q.r;
  }
} queries[Q];

int arr[N], n, answer[Q];
int freq_mo[1000005], ans_mo = 0;

void add_mo(int x) {
  ++freq_mo[x];
  if (freq_mo[x] == x) ++ans_mo;
}

void rem_mo(int x) {
  if (freq_mo[x] == x) --ans_mo;
  --freq_mo[x];
}

int get_ans_mo() {
  return ans_mo;
}

int main() {
  int q; scanf("%d %d", &n, &q);
  for (int i = 0; i < n; ++i) scanf("%d", &arr[i]);

  for (int i = 0; i < q; ++i) {
    int l, r; scanf("%d %d", &l, &r); --l; --r;
    queries[i] = Query(l, r, i);
  }
  sort(queries, queries + q);

  int l = 0, r = 0;
  add_mo(arr[0]);
  for (int i = 0; i < q; ++i) {
    while (l < queries[i].l) rem_mo(arr[l++]);
    while (l > queries[i].l) add_mo(arr[--l]);
    while (r < queries[i].r) add_mo(arr[++r]);
    while (r > queries[i].r) rem_mo(arr[r--]);
    answer[queries[i].id] = get_ans_mo();
  }

  for (int i = 0; i < q; ++i) printf("%d\n", answer[i]);
  return 0;
}
// 1469922775111


#include <bits/stdc++.h>

using namespace std;

#define fr(a, b, c) for(int a = b, __ = c; a < __; a++)

#define sd1(a) scanf("%d", &a)
#define sd2(a, b) scanf("%d%d", &a, &b)

#define dbg(x) cerr << ">>> " << x << endl;
#define _ << ", " <<

typedef long long ll;

const int maxn = 100111;
const int maxq = 100111;
const int BSZ  = 320;

vector<int> comp;
#define ADD(x) comp.push_back(x)
#define COMP(x) lower_bound(comp.begin(), comp.end(), x) - comp.begin()
#define BACK(x) comp[x]

ll sqr(ll x) { return x * x; }

struct Freq {
	ll arr[1000111];
	ll ans;

	Freq() {
		memset(arr, 0, sizeof arr);
		ans = 0;
	}

	void add(int x) {
		if(arr[x] == BACK(x)) ans--;
		arr[x]++;
		if(arr[x] == BACK(x)) ans++;
	}
	void rem(int x) {
		if(arr[x] == BACK(x)) ans--;
		arr[x]--;
		if(arr[x] == BACK(x)) ans++;
	}
} freq;

int n, q;
int v[maxn];
int l[maxq];
int r[maxq];
int mo[maxq];
ll ans[maxq];

bool cmp(int a, int b) {
	int Ba = l[a]/BSZ;
	int Bb = l[b]/BSZ;

	if(Ba != Bb) return Ba < Bb;

	return Ba & 1 ? r[a] < r[b] : r[a] > r[b];
}

void compress() {
	fr(i, 0, n) ADD(v[i]);

	sort(comp.begin(), comp.end());

	fr(i, 0, n) v[i] = COMP(v[i]);
}

int main() {
	sd2(n, q);

	fr(i, 0, n) sd1(v[i]);

	fr(i, 0, q) {
		sd1(l[i]);
		sd1(r[i]);
		l[i]--;
		r[i]--;
		mo[i] = i;
	}

	compress();

	sort(mo, mo + q, cmp);

	int L = 0, R = -1;
	fr(i, 0, q) {
		int l = ::l[mo[i]];
		int r = ::r[mo[i]];

		while(l < L) freq.add(v[--L]);
		while(r > R) freq.add(v[++R]);

		while(l > L) freq.rem(v[L++]);
		while(r < R) freq.rem(v[R--]);

		ans[mo[i]] = freq.ans;
	}

	fr(i, 0, q) {
		printf("%lld\n", ans[i]);
	}

	return 0;
}

// 1470681085605


#include <bits/stdc++.h>

#define N_MAX 100100
#define Q_MAX 100100

using namespace std;

struct Q {
  int l;
  int r;
  int i;
  int b;
};

int block_size = static_cast<int>(sqrt(N_MAX));
int num[N_MAX], ans[Q_MAX], answer = 0;
map <int, int> qtd;
Q query[Q_MAX];

bool cmp(Q x, Q y){
  if (x.b != y.b) {

    return x.b < y.b;
  }

  return x.r < y.r;
}

void add(int pos){

  qtd[num[pos]]++;
  if (qtd[num[pos]] == num[pos]) {
    answer++;

  } else if (qtd[num[pos]] == num[pos] + 1) {
    answer--;
  }
}

void remove(int pos){
  qtd[num[pos]]--;
  if (qtd[num[pos]] + 1 == num[pos]) {
    answer--;
  } else if (qtd[num[pos]] == num[pos]) {
    answer++;
  }
}

int main(){

  int n, q;

  scanf("%d %d", &n, &q);

  for (int i = 0; i < n; i++) {
    scanf("%d", &num[i]);
  }

  for (int i = 0; i < q; i++) {
    scanf("%d %d", &query[i].l, &query[i].r);
    query[i].l--; query[i].r--;
    query[i].b = i / block_size;
    query[i].i = i;
  }

  // sort(query, query + q, cmp);

  int curL = 0, curR = 0;

  for(int i = 0; i < q; i++){
    int l = query[i].l, r = query[i].r;

    while (curL > l) {
      add(--curL);
    }

    while (curL < l) {
      remove(curL++);
    }

    while (curR <= r) {
      add(curR++);
    }

    while (curR > r + 1) {
      remove(curR - 1);
      curR--;
    }

    ans[query[i].i] = answer;
  }

  for (int i = 0; i < q; i++) {
    printf("%d\n", ans[i]);
  }

  return 0;
}

// 1509029844264


#include <bits/stdc++.h>

using namespace std;

#define MAXN 100100

struct Query {
	int l,r,pos;
};

int block;
long long int arr[MAXN];
int aux[MAXN];
int answers[MAXN];
int ans = 0;

bool compare(Query A, Query B) {
	if (A.l / block != B.l / block)
		return A.l/block < B.l/block;
	return A.r < B.r;
}

void add(int position) {
	if (aux[position] == position)
		ans--;
	aux[position]++;
	if (aux[position] == position)
		ans++;
}

void remove(int position) {
	if (aux[position] == position)
		ans--;
	aux[position]--;
	if (aux[position] == position)
		ans++;
}

int main() {
	int n,q;
	scanf("%d %d", &n,&q);

	Query queries[q];
	block = sqrt(q);

	for (int i = 0; i < n; i++) {
		scanf("%lld", &arr[i]);
		if (arr[i] >= MAXN) arr[i] = MAXN-1;
	}

	for (int i = 0; i < q; i++) {
		Query a;
		scanf("%d %d", &a.l, &a.r);
		a.pos = i;
		a.l--;
		a.r--;
		queries[i] = a;
	}

	sort(queries, queries+q,compare);

	int currentL = 0;
	int currentR = -1;
	int L = 0;
	int R = 0;
	for (int i = 0; i < q; i++) {
		L = queries[i].l; R = queries[i].r;

		while (currentL < L) {
			remove(arr[currentL]);
			currentL++;
		}

		while (currentL > L) {
			currentL--;
			add(arr[currentL]);
		}

		while (currentR < R) {
			currentR++;
			add(arr[currentR]);
		}

		while (currentR > R) {
			remove(arr[currentR]);
			currentR--;
		}

		answers[queries[i].pos] = ans;
	}

	for (int i = 0; i < q; i++)
		printf("%d\n", answers[i]);

	return 0;
}
// 1495141876283


/*
 * Matheus Oliveira
 * 21/10/2017
 * 220B.cpp
*/

#include <bits/stdc++.h>
using namespace std;

#define MAXN 100010

typedef pair<int, int> P;

int intervalo, freq[MAXN], tam, queries, i, elementos[MAXN], p1, p2, l, r, counter, ans[MAXN], ordem;

bool compare(pair<P, int> f, pair<P, int> s) {
	if(f.first.first/intervalo == s.first.first/intervalo) return f.first.second < s.first.second;
	return f.first.first/intervalo < s.first.first/intervalo;
}

int main() {
	scanf("%d %d", &tam, &queries);
	intervalo = sqrt(tam);

	for(i=0; i < tam; i++) scanf("%d", &elementos[i]);
	vector< pair< P, int > > mos;

	for(i=0; i < queries; i++) {
		scanf("%d %d", &l, &r);
		mos.push_back( make_pair( make_pair(l-1, r-1), i ) );
	}

	sort(mos.begin(), mos.end(), compare);

	p1 = p2 = counter = 0;

	if(elementos[p1] < MAXN) {
		freq[ elementos[p1] ]++;
		if( freq[ elementos[p1] ] == elementos[p1] ) counter++;
	}

	for(i=0; i < queries; i++) {
		l = mos[i].first.first, r = mos[i].first.second, ordem = mos[i].second;

		// movimento do primeiro ponteiro
		while(p1 < l) {
			if(elementos[p1] < MAXN) {
				if( freq[ elementos[p1] ] == elementos[p1] ) counter--;
				freq[ elementos[p1] ]--;
				if( freq[ elementos[p1] ] == elementos[p1] ) counter++;
			}

			p1++;
		}
		while(p1 > l) {
			p1--;

			if(elementos[p1] < MAXN) {
				if( freq[ elementos[p1] ] == elementos[p1] ) counter--;
				freq[ elementos[p1] ]++;
				if( freq[ elementos[p1] ] == elementos[p1] ) counter++;
			}
		}

		//movimento do segundo ponteiro
		while(p2 < r) {
			p2++;

			if(elementos[p2] < MAXN) {
				if( freq[ elementos[p2] ] == elementos[p2] ) counter--;
				freq[ elementos[p2] ]++;
				if( freq[ elementos[p2] ] == elementos[p2] ) counter++;
			}
		}
		while(p2 > r) {
			if(elementos[p2] < MAXN) {
				if( freq[ elementos[p2] ] == elementos[p2] ) counter--;
				freq[ elementos[p2] ]--;
				if( freq[ elementos[p2] ] == elementos[p2] ) counter++;
			}

			p2--;
		}

		ans[ordem] = counter;
	}

	for(i=0; i < queries; i++) printf("%d\n", ans[i]);

	return 0;
}
// 1508594608683


#include <bits/stdc++.h>
#define MAX  100005
#define MAXS 325
#define MAXQ 100005
using namespace std;
int a[MAX], n, q, s;
int qi[MAXQ], qj[MAXQ], p[MAXQ], ans[MAXQ];
int occur[MAX] = {};
vector<int>group[MAXS];
bool comp(int a, int b);
bool comp2(int a, int b);
int main()
{
	scanf("%d %d", &n, &q);
	for(int i = 0;i < n;i++)
		scanf("%d", &a[i]);
	s = sqrt(n);
	if(s*s < n)
		s++;
	for(int i = 0;i < q;i++)
	{
		scanf("%d %d", &qi[i], &qj[i]);
		qi[i]--; qj[i]--;
		p[i] = i;
	}
	sort(p, p+q, comp);
	for(int i = 0;i < q;i++)
	{
		int gp = qi[p[i]]/s;
		group[gp].push_back(p[i]);
	}
	for(int i = 0;i < s;i++)
		sort(group[i].begin(), group[i].end(), comp2);
	int l = 0, r = 0, cont = 0;
	bool flag = false;
	for(int i = 0;i < s;i++)
	{
		for(int j = 0;j < group[i].size();j++)
		{
			int ql = qi[group[i][j]], qr = qj[group[i][j]];
			if(!flag)
			{
				for(int k = ql;k <= qr;k++)
					if(a[k] <= 100000)
					{
						if(occur[a[k]] == a[k])
							cont--;
						occur[a[k]]++;
						if(occur[a[k]] == a[k])
							cont++;
					}
				l = ql; r = qr;
				flag = true;
			}
			else
			{
				if(l < ql)
				{
					for(int k = l;k < ql;k++)
						if(a[k] <= 100000)
						{
							if(occur[a[k]] == a[k])
								cont--;
							occur[a[k]]--;
							if(occur[a[k]] == a[k])
								cont++;
						}
				}
				else if(l > ql)
				{
					for(int k = l-1;k >= ql;k--)
						if(a[k] <= 100000)
						{
							if(occur[a[k]] == a[k])
								cont--;
							occur[a[k]]++;
							if(occur[a[k]] == a[k])
								cont++;
						}
				}
				l = ql;
				if(r < qr)
				{
					for(int k = r+1;k <= qr;k++)
						if(a[k] <= 100000)
						{
							if(occur[a[k]] == a[k])
								cont--;
							occur[a[k]]++;
							if(occur[a[k]] == a[k])
								cont++;
						}
				}
				else if(r > qr)
				{
					for(int k = r;k > qr;k--)
						if(a[k] <= 100000)
						{
							if(occur[a[k]] == a[k])
								cont--;
							occur[a[k]]--;
							if(occur[a[k]] == a[k])
								cont++;
						}
				}
				r = qr;
			}
			ans[group[i][j]] = cont;
		}
	}
	for(int i = 0;i < q;i++)
		printf("%d\n", ans[i]);
	return 0;
}
bool comp(int a, int b)
{
	return qi[a] < qi[b];
}
bool comp2(int a, int b)
{
	return qj[a] < qj[b];
}
// 1478907596052


#include <bits/stdc++.h>
#define fr(a, b, c) for(int a = b; a < c; ++a)
#define pb push_back
#define MOD 9999991

using namespace std;

typedef long long ll;
typedef pair<ll, ll> ii;
typedef pair<ii, int> iii;

struct Q{
    int l, r, ix;
} q[200005];

int n, m, que;
int ansi[200005];
int cnt[10000005];
int ans, aux;

bool cmp(Q a, Q b) {
    if (a.l/que != b.l/que) return a.l < b.l;
    else return a.r < b.r;
}

void add(int x) {
    aux = ++cnt[x%MOD];
    if(aux == x) ++ans;
    else if (aux-1 == x) --ans;
}

void rem(int x) {
    aux = --cnt[x%MOD];
    if (aux == x) ++ans;
    else if (aux+1 == x) --ans;
}

int main() {
    cin >> n >> m;
    int a, b;
    int vec[100005];
    fr(i, 0, n) scanf("%d", &vec[i]);

    que = ceil(sqrt(n));

    fr(i, 0, m) {
        scanf("%d%d", &a, &b);
        --a; --b;
        q[i].l = a;
        q[i].r = b;
        q[i].ix = i;
    }

    sort(q, q+m, cmp);
    memset(cnt, 0, sizeof cnt);
    ans = 0;

    int curL = 0, curR = 0, l, r;
    fr(i, 0, m) {
        l = q[i].l;
        r = q[i].r;

        while (curL < l) {
            rem(vec[curL]);
            curL++;
        }
        while (curL > l) {
            add(vec[curL-1]);
            curL--;
        }
        while (curR <= r) {
            add(vec[curR]);
            curR++;
        }
        while (curR > r+1) {
            rem(vec[curR-1]);
            curR--;
        }

        ansi[q[i].ix] = ans;
    }

    fr(i, 0, m) printf("%d\n", ansi[i]);
}
// 1470410324865


#include <bits/stdc++.h>
#define MAXN 100010
#define MAXQ 100010
#define ll long long int
#define f first
#define s second
using namespace std;

int n, q, raiz;

struct query{
	int left, right, index;
};

bool compare(query a, query b){
	if (a.left/raiz != b.left/raiz) return a.left/raiz < b.left/raiz;
	return a.right > b.right;
}

int line[MAXN], qs[MAXQ], freqA[MAXN];

int main(){
	map <int, int > freq;
	scanf("%d %d", &n, &q);
	query atual[MAXQ];

	for (int i=0; i<n; i++){
		scanf("%d", &line[i]);

		if (line[i] > MAXN) {
			if (freq.find(line[i]) == freq.end()){
				freq.insert(pair <int, int > (line[i], 0));
			}
		}
	}

	raiz = sqrt(n) + 1;

	for (int i=0; i<q; i++){
		scanf("%d %d", &atual[i].left, &atual[i].right);
		atual[i].index = i;
	}

	sort(atual, atual + q, compare);

	int l=0, r=-1, k, objE, objD;

	int res=0, agora;

	for (int i=0; i<q; i++){
		objD = atual[i].right-1;
		objE = atual[i].left-1;

		while (r < objD) {
			r++;
			if (line[r] > MAXN)	agora = freq.find(line[r])->second;
			else agora = freqA[line[r]];

			if (agora == line[r]) res--;
			if (line[r] > MAXN) freq[line[r]] += 1;
			else freqA[line[r]] += 1;
			if (agora+1 == line[r]) res++;
		}

		while (objD < r) {
			if (line[r] > MAXN)	agora = freq.find(line[r])->second;
			else agora = freqA[line[r]];

			if (agora == line[r]) res--;
			if (line[r] > MAXN) freq[line[r]] -= 1;
			else freqA[line[r]] -= 1;
			if (agora-1 == line[r]) res++;
			r--;
		}

		while (l < objE) {
			if (line[l] > MAXN)	agora = freq.find(line[l])->second;
			else agora = freqA[line[l]];
			if (agora == line[l]) res--;
			if (line[l] > MAXN) freq[line[l]] -= 1;
			else freqA[line[l]] -= 1;
			if (agora-1 == line[l]) res++;
			l++;
		}

		while (objE < l){
			l--;
			if (line[l] > MAXN)	agora = freq.find(line[l])->second;
			else agora = freqA[line[l]];
			if (agora == line[l]) res--;
			if (line[l] > MAXN) freq[line[l]] += 1;
			else freqA[line[l]] += 1;
			if (agora+1 == line[l]) res++;
		}

		qs[atual[i].index] = res;
	}

	for (int i=0; i<q; i++){
		cout << qs[i] << endl;
	}

	return 0;
}
// 1508608753996


#include <bits/stdc++.h>

#define N_MAX 100100
#define Q_MAX 100100

using namespace std;

struct Q {
  int l;
  int r;
  int i;
};

int block_size = static_cast<int>(sqrt(N_MAX));
int num[N_MAX], ans[Q_MAX], answer = 0;
map <int, unsigned long long int> qtd;
Q query[Q_MAX];

bool cmp(Q x, Q y){
  if (x.l / block_size != y.l / block_size) {

    return x.l / block_size < y.l / block_size;
  }

  return x.r < y.r;
}

void add(int pos){

  qtd[num[pos]]++;
  if (qtd[num[pos]] == num[pos]) {
    answer++;

  } else if (qtd[num[pos]] == num[pos] + 1) {
    answer--;
  }
}

void remove(int pos){
  qtd[num[pos]]--;
  if (qtd[num[pos]] + 1 == num[pos]) {
    answer--;
  } else if (qtd[num[pos]] == num[pos]) {
    answer++;
  }
}

int main(){

  int n, q;

  scanf("%d %d", &n, &q);

  for (int i = 0; i < n; i++) {
    scanf("%d", &num[i]);
  }

  for (int i = 0; i < q; i++) {
    scanf("%d %d", &query[i].l, &query[i].r);
    query[i].l--; query[i].r--;
    query[i].i = i;
  }

  sort(query, query + q, cmp);

  int curL = 0, curR = 0;

  for(int i = 0; i < q; i++){
    int l = query[i].l, r = query[i].r;

    while (curL > l) {
      add(--curL);
    }

    while (curL < l) {
      remove(curL++);
    }

    while (curR <= r) {
      add(curR++);
    }

    while (curR > r + 1) {
      remove(curR - 1);
      curR--;
    }

    ans[query[i].i] = answer;
  }

  for (int i = 0; i < q; i++) {
    printf("%d\n", ans[i]);
  }

  return 0;
}

// 1509028981640


#include <iostream>
#include <string>
#include <set>
#include <vector>
#include <algorithm>
#include <math.h>
#include <map>
using namespace std;

float root;

struct Interval
{
	vector<int> interval;
	int position;
	int answer;
	Interval(){
		interval.resize(2);
	}
};

bool compareIntervals(Interval &i,Interval &j)
{
    int group1 = ceil(i.interval[0]/root);
    int group2 = ceil(j.interval[0]/root);

    if(group1!=group2){
        return group1<group2;
    }

   int size1 = i.interval[1]-i.interval[0];
   int size2 = j.interval[1]-j.interval[0];

   if(size1==size2){
       return i.interval[1]<j.interval[1];
   }

   return size1<size2;
};

bool comparePositions(Interval &i,Interval &j)
{
    return i.position<j.position;
};

int main()
{
	int n; scanf("%d",&n);
	int numOfQueries; scanf("%d", &numOfQueries);
	root = ceil(sqrt(n));

	vector<Interval> intervals(numOfQueries);
	int maxNum = 100001;
	vector<int> freq(maxNum);
	vector<int> nums(n);

	for(int i = 0; i < n; i++){
		scanf("%d",&nums[i]);
	}

	for(int i = 0; i < numOfQueries; i++)
	{
		intervals[i].position = i;
		scanf("%d",&intervals[i].interval[0]);
		scanf("%d",&intervals[i].interval[1]);
	}

	sort(intervals.begin(), intervals.end(), compareIntervals);

	int oldLeft = intervals[0].interval[0]-1;
	int oldRight = intervals[0].interval[1]-1;
	int sum = 0;

	for(int i = oldLeft; i <= oldRight; i++)
	{
		int num = nums[i];

		if(num<maxNum)
		{
			freq[num]++;

			if(freq[num]-1==num){
				sum--;
			}
			else if(freq[num]==num){
				sum++;
			}
		}

	}

	for(int i = 0; i < numOfQueries; i++)
	{
		int newLeft = intervals[i].interval[0]-1;
		int newRight = intervals[i].interval[1]-1;

		if(oldLeft<newLeft){
			for(int j = oldLeft; j < newLeft; j++)
			{
				int num = nums[j];

				if(num<maxNum)
				{
					freq[num]--;

					if(freq[num]+1==num){
						sum--;
					}
					else if(freq[num]==num){
						sum++;
					}
				}

			}
		}
		else if(oldLeft>newLeft){
			for(int j = oldLeft-1; j >= newLeft; j--)
			{
				int num = nums[j];

				if(num<maxNum)
				{
					freq[num]++;

					if(freq[num]-1==num){
						sum--;
					}
					else if(freq[num]==num){
						sum++;
					}
				}
			}
		}

		if(oldRight<newRight){
			for(int j = oldRight+1; j <= newRight; j++)
			{
				int num = nums[j];

				if(num<maxNum)
				{
					freq[num]++;

					if(freq[num]-1==num){
						sum--;
					}
					else if(freq[num]==num){
						sum++;
					}
				}
			}
		}
		else if(oldRight>newRight){
			for(int j = oldRight; j > newRight; j--)
			{
				int num = nums[j];

				if(num<maxNum)
				{
					freq[num]--;

					if(freq[num]+1==num){
						sum--;
					}
					else if(freq[num]==num){
						sum++;
					}
				}
			}
		}

		intervals[i].answer = sum;

		oldLeft = newLeft;
		oldRight = newRight;
	}

	sort(intervals.begin(), intervals.end(), comparePositions);

	for(int i = 0; i < numOfQueries; i++){
		printf("%d\n", intervals[i].answer);
	}
}

// 1508973350592


#include<bits/stdc++.h>
#define MAX 100002
#define gc getchar
using namespace std;

int block,ans=0,cnt[MAX]={0};

int fast() {
    int val = 0;
    char c = gc();
    while (c<33) c = gc();
    while (c>33) val = (val<<1) + (val<<3) + (c-'0'), c = gc();
    return val;
}

struct qry{
    int l;
    int r;
    int pos;
};

int mosort(qry a,qry b)
{
if(a.l/block==b.l/block)
    return a.l/block<b.l/block;
return a.r<b.r;
}

void add(int index)
{
    if(cnt[index]==index)
        ans--;
    cnt[index]++;
    if(cnt[index]==index)
        ans++;
}

void del(int index)
{
    if(cnt[index]==index)
        ans--;
        cnt[index]--;
        if(cnt[index]==index)
            ans++;
}

int main()
{
    int n,m;
    n=fast();m=fast();
    block=sqrt(n);
    int arr[n+1],answer[m+1];
    qry query[m+1];
    for(int i=1;i<=n;i++)
        arr[i]=fast();
    for(int i=1;i<=m;i++)
    {
        query[i].l=fast();query[i].r=fast();
        query[i].pos=i;
    }
    int currl=1,currr=0;
    sort(query+1,query+1+m,mosort);
    for(int i=1;i<=m;i++)
    {
        int l=query[i].l;
        int r=query[i].r;
        while(currl<l)
        {
            if(arr[currl]<=n)
                del(arr[currl]);
                currl++;
        }
        while(currl>l)
        {
            currl--;
            if(arr[currl]<=n)
                add(arr[currl]);
        }
        while(currr<r)
        {
            currr++;
            if(arr[currr]<=n)
                add(arr[currr]);
        }
        while(currr>r)
        {
            if(arr[currr]<=n)
                del(arr[currr]);
                currr--;
        }
        answer[query[i].pos]=ans;
    }
    for(int i=1;i<=m;i++)
        printf("%d\n",answer[i]);
    return 0;
}


#include<bits/stdc++.h>
#define MAX 100002
#define gc getchar
using namespace std;

int block,ans=0,cnt[MAX]={0};

int fast() {
    int val = 0;
    char c = gc();
    while (c<33) c = gc();
    while (c>33) val = (val<<1) + (val<<3) + (c-'0'), c = gc();
    return val;
}

struct qry{
    int l;
    int r;
    int pos;
};

int mosort(qry a,qry b)
{
if(a.l/block==b.l/block)
    return a.l/block<b.l/block;
return a.r<b.r;
}

void add(int index)
{
    cnt[index]++;
    if(cnt[index]==index)
        ans++;
}

void del(int index)
{
    if(cnt[index]==index)
        ans--;
        cnt[index]--;
        if(cnt[index]==index)
            ans++;
}

int main()
{
    int n,m;
    n=fast();m=fast();
    block=sqrt(n);
    int arr[n+1],answer[m+1];
    qry query[m+1];
    for(int i=1;i<=n;i++)
        arr[i]=fast();
    for(int i=1;i<=m;i++)
    {
        query[i].l=fast();query[i].r=fast();
        query[i].pos=i;
    }
    int currl=1,currr=0;
    sort(query+1,query+1+m,mosort);
    for(int i=1;i<=m;i++)
    {
        int l=query[i].l;
        int r=query[i].r;
        while(currl<l)
        {
            if(arr[currl]<=n)
                del(arr[currl]);
                currl++;
        }
        while(currl>l)
        {
            currl--;
            if(arr[currl]<=n)
                add(arr[currl]);
        }
        while(currr<r)
        {
            currr++;
            if(arr[currr]<=n)
                add(arr[currr]);
        }
        while(currr>r)
        {
            if(arr[currr]<=n)
                del(arr[currr]);
                currr--;
        }
        answer[query[i].pos]=ans;
    }
    for(int i=1;i<=m;i++)
        printf("%d\n",answer[i]);
    return 0;
}


#include<bits/stdc++.h>
#define gc getchar
#define MAX 100005
using namespace std;

int block,ans=0,cnt[MAX]={0};

int fast() {
    int val = 0;
    char c = gc();
    while (c<33) c = gc();
    while (c>33) val = (val<<1) + (val<<3) + (c-'0'), c = gc();
    return val;
}

struct qry{
    int l;
    int r;
    int pos;
};

int mosort(qry a,qry b)
{
if(a.l/block==b.l/block)
    return a.r<b.r;
return a.l/block<b.l/block;
}

void add(int index)
{
    if(cnt[index]==index)
        ans--;
    cnt[index]++;
    if(cnt[index]==index)
        ans++;
}

void del(int index)
{
    if(cnt[index]==index)
        ans--;
    cnt[index]--;
    if(cnt[index]==index)
        ans++;
}

int main()
{
    int n,m;
    n=fast();m=fast();
    block=sqrt(n);
    int arr[n+1],answer[m+1];
    qry query[m+1];
    for(int i=0;i<n;i++)
        arr[i]=fast();
    for(int i=0;i<m;i++)
    {
        query[i].l=fast()-1;query[i].r=fast()-1;
        query[i].pos=i;
    }
    int currl=0,currr=-1;
    sort(query,query+m,mosort);
    for(int i=0;i<m;i++)
    {
        int l=query[i].l;
        int r=query[i].r;
        while(currl<l)
        {
            if(arr[currl]<=n)
                del(arr[currl]);
                currl++;
        }
        while(currl>l)
        {
            currl--;
            if(arr[currl]<=n)
                add(arr[currl]);
        }
        while(currr<r)
        {
            currr++;
            if(arr[currr]<=n)
                add(arr[currr]);
        }
        while(currr>r)
        {
            if(arr[currr]<=n)
                del(arr[currr]);
                currr--;
        }
        answer[query[i].pos]=ans;
    }
    for(int i=0;i<m;i++)
        printf("%d\n",answer[i]);
    return 0;
}


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;

public class Main {

	private static final String NO = "NO";
	private static final String YES = "YES";
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	private static final long MOD = 998244353L;
	private static final int MAX = 100000;

	void solve() {
		StringBuffer sb = new StringBuffer();

		int N = ni();
		while (N-- > 0) {
			char[] a = ns().toCharArray();
			int d1 = get(a, 'W', 'S');
			int d2 = get(a, 'A', 'D');

			int ans = d1 * d2;
//			tr(d1, d2);
			if (d1 > 2)
				ans = (d1 - 1) * d2;
			if (d2 > 2)
				ans = Math.min(ans, (d2 - 1) * d1);
			out.println(ans);
		}
	}

	private int get(char[] a, char d1, char d2) {
		int cur = 0;
		int min = 0;
		int max = 0;
		for (char c : a) {
			if (d1 == c)
				cur++;
			else if (d2 == c)
				cur--;
			min = Math.min(min, cur);
			max = Math.max(max, cur);
		}
		return max - min + 1;
	}

	long power(long a, long b) {
		long x = 1, y = a;
		while (b > 0) {
			if (b % 2 != 0) {
				x = (x * y) % MOD;
			}
			y = (y * y) % MOD;
			b /= 2;
		}
		return x % MOD;
	}

	private long gcd(long a, long b) {
		while (a != 0) {
			long tmp = b % a;
			b = a;
			a = tmp;
		}
		return b;
	}

	void run() throws Exception {
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		if (!INPUT.isEmpty())
			tr(System.currentTimeMillis() - s + "ms");
	}

	public static void main(String[] args) throws Exception {
		new Main().run();
	}

	private byte[] inbuf = new byte[1024];
	public int lenbuf = 0, ptrbuf = 0;
	private boolean vis[];

	private int readByte() {
		if (lenbuf == -1)
			throw new InputMismatchException();
		if (ptrbuf >= lenbuf) {
			ptrbuf = 0;
			try {
				lenbuf = is.read(inbuf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (lenbuf <= 0)
				return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) {
		return !(c >= 33 && c <= 126);
	}

	private int skip() {
		int b;
		while ((b = readByte()) != -1 && isSpaceChar(b))
			;
		return b;
	}

	private double nd() {
		return Double.parseDouble(ns());
	}

	private char nc() {
		return (char) skip();
	}

	private String ns() {
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
									// ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n) {
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while (p < n) {
			if (!(isSpaceChar(b)))
				buf[p++] = (char) b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m) {
		char[][] map = new char[n][];
		for (int i = 0; i < n; i++)
			map[i] = ns(m);
		return map;
	}

	private int[] na(int n) {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private Integer[] na2(int n) {
		Integer[] a = new Integer[n];
		for (int i = 0; i < n; i++)
			a[i] = ni();
		return a;
	}

	private int[][] na(int n, int m) {
		int[][] a = new int[n][];
		for (int i = 0; i < n; i++)
			a[i] = na(m);
		return a;
	}

	private Integer[][] na2(int n, int m) {
		Integer[][] a = new Integer[n][];
		for (int i = 0; i < n; i++)
			a[i] = na2(m);
		return a;
	}

	private int ni() {
		int num = 0, b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl() {
		long num = 0;
		int b;
		boolean minus = false;
		while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
			;
		if (b == '-') {
			minus = true;
			b = readByte();
		}

		while (true) {
			if (b >= '0' && b <= '9') {
				num = num * 10 + (b - '0');
			} else {
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private static void tr(Object... o) {
		System.out.println(Arrays.deepToString(o));
	}
}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	void run(){
		int q=in.nextInt();
		for(int i=0;i<q;i++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	long ret=0;
	long ml,mr,mu,md;
	boolean v,h;
	void work() {
		ml=0;
		mr=0;
		mu=0;
		md=0;
		v=false;
		h=false;
		String s=in.next();
		int n=s.length();
		int[] p=new int[2];
		for(int i=0;i<n;i++) {
			char c=s.charAt(i);
			if(c=='W') p[0]--;
			else if(c=='S') p[0]++;
			else if(c=='A') p[1]--;
			else p[1]++;
			ml=Math.min(p[1], ml);
			mr=Math.max(p[1], mr);
			mu=Math.min(p[0], mu);
			md=Math.max(p[0], md);
		}
		dfs(s,0,0,0,0,0,0,0);
		long ret=(mr-ml+1)*(md-mu+1);
		if(h&&mr-ml>1) {//至少移一步
			ret=Math.min(ret,(md-mu+1)*(mr-ml));
		}
		if(v&&md-mu>1) {
			ret=Math.min(ret,(mr-ml+1)*(md-mu));
		}
		out.println(ret);
	}
	private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) {
		if(index==s.length()) {
			return new int[] {y,y,x,x};
		}
		char c=s.charAt(index);
		int nx=x,ny=y;
		if(c=='W') nx--;
		else if(c=='S') nx++;
		else if(c=='A') ny--;
		else ny++;
		int nl=Math.min(ny, cl);
		int nr=Math.max(ny, cr);
		int nu=Math.min(nx, cu);
		int nd=Math.max(nx, cd);
		int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d
		p[0]=Math.min(ny, p[0]);
		p[1]=Math.max(ny, p[1]);
		p[2]=Math.min(nx, p[2]);
		p[3]=Math.max(nx, p[3]);

		if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) {
			h=true;
		}
		if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) {
			v=true;
		}

		return p;

	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		if(st==null || !st.hasMoreElements())
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	int e=0;
	void run(){
		int q=in.nextInt();
		for(;e<q;e++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	long ret=0;
	int ml,mr,mu,md;
	boolean v,h;
	void work() {
		ml=0;
		mr=0;
		mu=0;
		md=0;
		String s=in.next();
		int n=s.length();
		int[] p=new int[2];
		for(int i=0;i<n;i++) {
			char c=s.charAt(i);
			if(c=='W') p[0]--;
			else if(c=='S') p[0]++;
			else if(c=='A') p[1]--;
			else p[1]++;
			ml=Math.min(p[1], ml);
			mr=Math.max(p[1], mr);
			mu=Math.min(p[0], mu);
			md=Math.max(p[0], md);
		}
		dfs(s,0,0,0,0,0,0,0);
		long ret=(mr-ml+1)*(md-mu+1);
		if(h&&mr-ml>1) {//至少移一步
			ret=Math.min(ret,(md-mu+1)*(mr-ml));
		}
		if(v&&md-mu>1) {
			ret=Math.min(ret,(mr-ml+1)*(md-mu));
		}
		if(e==94) {
			out.println(s+",,,,"+ret);
		}
		out.println(ret);
	}
	private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) {
		if(index==s.length()-1) {
			return new int[] {x,x,y,y};
		}
		char c=s.charAt(index);
		int nx=x,ny=y;
		if(c=='W') nx--;
		else if(c=='S') nx++;
		else if(c=='A') ny--;
		else ny++;
		int nl=Math.min(ny, cl);
		int nr=Math.max(ny, cr);
		int nu=Math.min(nx, cu);
		int nd=Math.max(nx, cd);
		int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d
		p[0]=Math.min(ny, p[0]);
		p[1]=Math.max(ny, p[1]);
		p[2]=Math.min(nx, p[2]);
		p[3]=Math.max(nx, p[3]);

		if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) {
			h=true;
		}
		if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) {
			v=true;
		}

		return p;

	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		if(st==null || !st.hasMoreElements())
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	void run(){
		int q=in.nextInt();
		for(int i=0;i<q;i++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	long ret=0;
	int ml,mr,mu,md;
	boolean v,h;
	void work() {
		ml=0;
		mr=0;
		mu=0;
		md=0;
		v=false;
		h=false;
		String s=in.next();
		int n=s.length();
		int[] p=new int[2];
		for(int i=0;i<n;i++) {
			char c=s.charAt(i);
			if(c=='W') p[0]--;
			else if(c=='S') p[0]++;
			else if(c=='A') p[1]--;
			else p[1]++;
			ml=Math.min(p[1], ml);
			mr=Math.max(p[1], mr);
			mu=Math.min(p[0], mu);
			md=Math.max(p[0], md);
		}
		dfs(s,0,0,0,0,0,0,0);
		long ret=(mr-ml+1)*(md-mu+1);
		if(h&&mr-ml>1) {//至少移一步
			ret=Math.min(ret,(md-mu+1)*(mr-ml));
		}
		if(v&&md-mu>1) {
			ret=Math.min(ret,(mr-ml+1)*(md-mu));
		}
		out.println(ret);
	}
	private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) {
		if(index==s.length()) {
			return new int[] {x,x,y,y};
		}
		char c=s.charAt(index);
		int nx=x,ny=y;
		if(c=='W') nx--;
		else if(c=='S') nx++;
		else if(c=='A') ny--;
		else ny++;
		int nl=Math.min(ny, cl);
		int nr=Math.max(ny, cr);
		int nu=Math.min(nx, cu);
		int nd=Math.max(nx, cd);
		int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d
		p[0]=Math.min(ny, p[0]);
		p[1]=Math.max(ny, p[1]);
		p[2]=Math.min(nx, p[2]);
		p[3]=Math.max(nx, p[3]);

		if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) {
			h=true;
		}
		if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) {
			v=true;
		}

		return p;

	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		if(st==null || !st.hasMoreElements())
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	void run(){
		int q=in.nextInt();
		for(int i=0;i<q;i++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	long ret=0;
	int ml,mr,mu,md;
	boolean v,h;
	void work() {
		ml=0;
		mr=0;
		mu=0;
		md=0;
		v=false;
		h=false;
		String s=in.next();
		int n=s.length();
		int[] p=new int[2];
		for(int i=0;i<n;i++) {
			char c=s.charAt(i);
			if(c=='W') p[0]--;
			else if(c=='S') p[0]++;
			else if(c=='A') p[1]--;
			else p[1]++;
			ml=Math.min(p[1], ml);
			mr=Math.max(p[1], mr);
			mu=Math.min(p[0], mu);
			md=Math.max(p[0], md);
		}
		dfs(s,0,0,0,0,0,0,0);
		long ret=(mr-ml+1)*(md-mu+1);
		if(h&&mr-ml>1) {//至少移一步
			ret=Math.min(ret,(md-mu+1)*(mr-ml));
		}
		if(v&&md-mu>1) {
			ret=Math.min(ret,(mr-ml+1)*(md-mu));
		}
		out.println(ret);
	}
	private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) {
		if(index==s.length()-1) {
			return new int[] {x,x,y,y};
		}
		char c=s.charAt(index);
		int nx=x,ny=y;
		if(c=='W') nx--;
		else if(c=='S') nx++;
		else if(c=='A') ny--;
		else ny++;
		int nl=Math.min(ny, cl);
		int nr=Math.max(ny, cr);
		int nu=Math.min(nx, cu);
		int nd=Math.max(nx, cd);
		int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d
		p[0]=Math.min(ny, p[0]);
		p[1]=Math.max(ny, p[1]);
		p[2]=Math.min(nx, p[2]);
		p[3]=Math.max(nx, p[3]);

		if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) {
			h=true;
		}
		if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) {
			v=true;
		}

		return p;

	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		if(st==null || !st.hasMoreElements())
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	int q=in.nextInt();
	void run(){

		for(int i=0;i<q;i++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	long ret=0;
	int ml,mr,mu,md;
	boolean v,h;
	void work() {
		ml=0;
		mr=0;
		mu=0;
		md=0;
		String s=in.next();
		int n=s.length();
		int[] p=new int[2];
		for(int i=0;i<n;i++) {
			char c=s.charAt(i);
			if(c=='W') p[0]--;
			else if(c=='S') p[0]++;
			else if(c=='A') p[1]--;
			else p[1]++;
			ml=Math.min(p[1], ml);
			mr=Math.max(p[1], mr);
			mu=Math.min(p[0], mu);
			md=Math.max(p[0], md);
		}
		dfs(s,0,0,0,0,0,0,0);
		long ret=(mr-ml+1)*(md-mu+1);
		if(h&&mr-ml>1) {//至少移一步
			ret=Math.min(ret,(md-mu+1)*(mr-ml));
		}
		if(v&&md-mu>1) {
			ret=Math.min(ret,(mr-ml+1)*(md-mu));
		}
		if(q==94) {
			out.println(s+",,,,"+ret);
		}
		out.println(ret);
	}
	private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) {
		if(index==s.length()-1) {
			return new int[] {x,x,y,y};
		}
		char c=s.charAt(index);
		int nx=x,ny=y;
		if(c=='W') nx--;
		else if(c=='S') nx++;
		else if(c=='A') ny--;
		else ny++;
		int nl=Math.min(ny, cl);
		int nr=Math.max(ny, cr);
		int nu=Math.min(nx, cu);
		int nd=Math.max(nx, cd);
		int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d
		p[0]=Math.min(ny, p[0]);
		p[1]=Math.max(ny, p[1]);
		p[2]=Math.min(nx, p[2]);
		p[3]=Math.max(nx, p[3]);

		if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) {
			h=true;
		}
		if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) {
			v=true;
		}

		return p;

	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		if(st==null || !st.hasMoreElements())
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	void run(){
		int q=in.nextInt();
		for(int i=0;i<q;i++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	long ret=0;
	int ml,mr,mu,md;
	boolean v,h;
	void work() {
		ml=0;
		mr=0;
		mu=0;
		md=0;
		String s=in.next();
		int n=s.length();
		int[] p=new int[2];
		for(int i=0;i<n;i++) {
			char c=s.charAt(i);
			if(c=='W') p[0]--;
			else if(c=='S') p[0]++;
			else if(c=='A') p[1]--;
			else p[1]++;
			ml=Math.min(p[1], ml);
			mr=Math.max(p[1], mr);
			mu=Math.min(p[0], mu);
			md=Math.max(p[0], md);
		}
		dfs(s,0,0,0,0,0,0,0);
		long ret=(mr-ml+1)*(md-mu+1);
		if(h&&mr-ml>1) {//至少移一步
			ret=Math.min(ret,(md-mu+1)*(mr-ml));
		}
		if(v&&md-mu>1) {
			ret=Math.min(ret,(mr-ml+1)*(md-mu));
		}
		out.println(ret);
	}
	private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) {
		if(index==s.length()-1) {
			return new int[] {x,x,y,y};
		}
		char c=s.charAt(index);
		int nx=x,ny=y;
		if(c=='W') nx--;
		else if(c=='S') nx++;
		else if(c=='A') ny--;
		else ny++;
		int nl=Math.min(ny, cl);
		int nr=Math.max(ny, cr);
		int nu=Math.min(nx, cu);
		int nd=Math.max(nx, cd);
		int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d
		p[0]=Math.min(ny, p[0]);
		p[1]=Math.max(ny, p[1]);
		p[2]=Math.min(nx, p[2]);
		p[3]=Math.max(nx, p[3]);

		if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) {
			h=true;
		}
		if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) {
			v=true;
		}

		return p;

	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		if(st==null || !st.hasMoreElements())
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	void run(){
		int q=in.nextInt();
		for(int i=0;i<q;i++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	long ret=0;
	int ml,mr,mu,md;
	boolean v,h;
	void work() {
		ml=0;
		mr=0;
		mu=0;
		md=0;
		String s=in.next();
		int n=s.length();
		int[] p=new int[2];
		for(int i=0;i<n;i++) {
			char c=s.charAt(i);
			if(c=='W') p[0]--;
			else if(c=='S') p[0]++;
			else if(c=='A') p[1]--;
			else p[1]++;
			ml=Math.min(p[1], ml);
			mr=Math.max(p[1], mr);
			mu=Math.min(p[0], mu);
			md=Math.max(p[0], md);
		}
		dfs(s,0,0,0,0,0,0,0);
		long ret=(mr-ml+1)*(md-mu+1);
		if(h&&mr-ml>1) {//至少移一步
			ret=Math.min(ret,(md-mu+1)*(mr-ml));
		}
		if(v&&md-mu>1) {
			ret=Math.min(ret,(mr-ml+1)*(md-mu));
		}
		out.println(ret);
	}
	private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) {
		if(index==s.length()-1) {
			return new int[] {x,x,y,y};
		}
		char c=s.charAt(index);
		int nx=x,ny=y;
		if(c=='W') nx--;
		else if(c=='S') nx++;
		else if(c=='A') ny--;
		else ny++;
		int nl=Math.min(ny, cl);
		int nr=Math.max(ny, cr);
		int nu=Math.min(nx, cu);
		int nd=Math.max(nx, cd);
		int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d
		if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) {
			h=true;
		}
		if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) {
			v=true;
		}
		p[0]=Math.min(ny, p[0]);
		p[1]=Math.max(ny, p[1]);
		p[2]=Math.min(nx, p[2]);
		p[3]=Math.max(nx, p[3]);

		return p;

	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		if(st==null || !st.hasMoreElements())
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	void run(){
		int q=in.nextInt();
		for(int i=0;i<q;i++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	long ret=0;
	int ml,mr,mu,md;
	boolean v,h;
	void work() {
		ml=0;
		mr=0;
		mu=0;
		md=0;
		String s=in.next();
		int n=s.length();
		int[] p=new int[2];
		for(int i=0;i<n;i++) {
			char c=s.charAt(i);
			if(c=='W') p[0]--;
			else if(c=='S') p[0]++;
			else if(c=='A') p[1]--;
			else p[1]++;
			ml=Math.min(p[1], ml);
			mr=Math.max(p[1], mr);
			mu=Math.min(p[0], mu);
			md=Math.max(p[0], md);
		}
		dfs(s,0,0,0,0,0,0,0);
		long ret=(mr-ml+1)*(md-mu+1);
		if(v&&mr-ml>1) {//至少移一步
			ret=Math.min(ret,(md-mu)*(mr-ml+1));
		}
		if(h&&md-mu>1) {
			ret=Math.min(ret,(mr-ml)*(md-mu+1));
		}
		out.println(ret);
	}
	private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) {
		if(index==s.length()-1) {
			return new int[] {x,x,y,y};
		}
		char c=s.charAt(index);
		int nx=x,ny=y;
		if(c=='W') nx--;
		else if(c=='S') nx++;
		else if(c=='A') ny--;
		else ny++;
		int nl=Math.min(ny, cl);
		int nr=Math.max(ny, cr);
		int nu=Math.min(nx, cu);
		int nd=Math.max(nx, cd);
		int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d
		if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) {
			h=true;
		}
		if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) {
			v=true;
		}
		p[0]=Math.min(ny, p[0]);
		p[1]=Math.max(ny, p[1]);
		p[2]=Math.min(nx, p[2]);
		p[3]=Math.max(nx, p[3]);

		return p;

	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		if(st==null || !st.hasMoreElements())
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


import java.util.*;
import java.io.*;

public class Main {
	public static void main(String args[]) {new Main().run();}

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	void run(){
		int q=in.nextInt();
		for(int i=0;i<q;i++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	long ret=0;
	int ml,mr,mu,md;
	boolean v,h;
	void work() {
		ml=0;
		mr=0;
		mu=0;
		md=0;
		v=false;
		h=false;
		String s=in.next();
		int n=s.length();
		int[] p=new int[2];
		for(int i=0;i<n;i++) {
			char c=s.charAt(i);
			if(c=='W') p[0]--;
			else if(c=='S') p[0]++;
			else if(c=='A') p[1]--;
			else p[1]++;
			ml=Math.min(p[1], ml);
			mr=Math.max(p[1], mr);
			mu=Math.min(p[0], mu);
			md=Math.max(p[0], md);
		}
		dfs(s,0,0,0,0,0,0,0);
		long ret=(mr-ml+1)*(md-mu+1);
		if(h&&mr-ml>1) {//至少移一步
			ret=Math.min(ret,(md-mu+1)*(mr-ml));
		}
		if(v&&md-mu>1) {
			ret=Math.min(ret,(mr-ml+1)*(md-mu));
		}
		out.println(ret);
	}
	private int[] dfs(String s, int index, int x, int y, int cl, int cr, int cu, int cd) {
		if(index==s.length()) {
			return new int[] {y,y,x,x};
		}
		char c=s.charAt(index);
		int nx=x,ny=y;
		if(c=='W') nx--;
		else if(c=='S') nx++;
		else if(c=='A') ny--;
		else ny++;
		int nl=Math.min(ny, cl);
		int nr=Math.max(ny, cr);
		int nu=Math.min(nx, cu);
		int nd=Math.max(nx, cd);
		int[] p=dfs(s,index+1,nx,ny,nl,nr,nu,nd);//l,r,u,d
		p[0]=Math.min(ny, p[0]);
		p[1]=Math.max(ny, p[1]);
		p[2]=Math.min(nx, p[2]);
		p[3]=Math.max(nx, p[3]);

		if((cl!=ml||cr!=mr)&&(p[0]!=ml||p[1]!=mr)) {
			h=true;
		}
		if(((cu!=mu||cd!=md))&&(p[2]!=mu||p[3]!=md)) {
			v=true;
		}

		return p;

	}
}

class FastReader
{
	BufferedReader br;
	StringTokenizer st;

	public FastReader()
	{
		br=new BufferedReader(new InputStreamReader(System.in));
	}

	public String next()
	{
		if(st==null || !st.hasMoreElements())
		{
			try {
				st = new StringTokenizer(br.readLine());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return st.nextToken();
	}

	public int nextInt()
	{
		return Integer.parseInt(next());
	}

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}


import java.io.*;
import java.nio.CharBuffer;
import java.util.NoSuchElementException;

public class P1202C {

    public static void main(String[] args) {
        SimpleScanner scanner = new SimpleScanner(System.in);
        PrintWriter writer = new PrintWriter(System.out);

        int caseNum = scanner.nextInt();
        while (caseNum-- > 0) {
            char[] s = scanner.next().toCharArray();
            int n = s.length;
            int top = 0, bottom = 0, right = 0, left = 0;
            for (int i = 0, x = 0, y = 0; i < n; ++i) {
                if (s[i] == 'W') {
                    ++x;
                    top = Math.max(top, x);
                } else if (s[i] == 'S') {
                    --x;
                    bottom = Math.min(x, bottom);
                } else if (s[i] == 'A') {
                    --y;
                    left = Math.min(left, y);
                } else { //s[i] == 'D'
                    ++y;
                    right = Math.max(right, y);
                }
            }
            long ans = (long) (top - bottom + 1) * (right - left + 1);
            if (top - bottom > 1)
                ans = Math.min((long) (top - bottom) * (right - left + 1), ans);
            if (right - left > 1)
                ans = Math.min((long) (top - bottom + 1) * (right - left), ans);
            writer.println(ans);
        }

        writer.close();
    }

    private static class SimpleScanner {

        private static final int BUFFER_SIZE = 10240;

        private Readable in;
        private CharBuffer buffer;
        private boolean eof;

        SimpleScanner(InputStream in) {
            this.in = new BufferedReader(new InputStreamReader(in));
            buffer = CharBuffer.allocate(BUFFER_SIZE);
            buffer.limit(0);
            eof = false;
        }

        private char read() {
            if (!buffer.hasRemaining()) {
                buffer.clear();
                int n;
                try {
                    n = in.read(buffer);
                } catch (IOException e) {
                    n = -1;
                }
                if (n <= 0) {
                    eof = true;
                    return '\0';
                }
                buffer.flip();
            }
            return buffer.get();
        }

        void checkEof() {
            if (eof)
                throw new NoSuchElementException();
        }

        char nextChar() {
            checkEof();
            char b = read();
            checkEof();
            return b;
        }

        String next() {
            char b;
            do {
                b = read();
                checkEof();
            } while (Character.isWhitespace(b));
            StringBuilder sb = new StringBuilder();
            do {
                sb.append(b);
                b = read();
            } while (!eof && !Character.isWhitespace(b));
            return sb.toString();
        }

        int nextInt() {
            return Integer.valueOf(next());
        }

        long nextLong() {
            return Long.valueOf(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}


import java.io.*;
import java.nio.CharBuffer;
import java.util.NoSuchElementException;

public class P1202C {

    public static void main(String[] args) {
        SimpleScanner scanner = new SimpleScanner(System.in);
        PrintWriter writer = new PrintWriter(System.out);

        int caseNum = scanner.nextInt();
        while (caseNum-- > 0) {
            char[] s = scanner.next().toCharArray();
            int n = s.length;
            int[][] minR = new int[2][n + 1];
            int[][] maxR = new int[2][n + 1];
            int[][] minC = new int[2][n + 1];
            int[][] maxC = new int[2][n + 1];
            int[] r = new int[n + 1];
            int[] c = new int[n + 1];
            for (int i = 1; i <= n; ++i) {
                r[i] = r[i - 1];
                c[i] = c[i - 1];
                if (s[i - 1] == 'W')
                    --r[i];
                else if (s[i - 1] == 'S')
                    ++r[i];
                else if (s[i - 1] == 'A')
                    --c[i];
                else //s[i - 1] == 'D'
                    ++c[i];
                minR[0][i] = Math.min(minR[0][i - 1], r[i]);
                maxR[0][i] = Math.max(maxR[0][i - 1], r[i]);
                minC[0][i] = Math.min(minC[0][i - 1], c[i]);
                maxC[0][i] = Math.max(maxC[0][i - 1], c[i]);
            }
            minR[1][n] = r[n];
            maxR[1][n] = r[n];
            minC[1][n] = c[n];
            maxC[1][n] = c[n];
            for (int i = n - 1; i >= 0; --i) {
                minR[1][i] = Math.min(minR[1][i + 1], r[i]);
                maxR[1][i] = Math.max(maxR[1][i + 1], r[i]);
                minC[1][i] = Math.min(minC[1][i + 1], c[i]);
                maxC[1][i] = Math.max(maxC[1][i + 1], c[i]);
            }
            long height = maxR[0][n] - minR[0][n] + 1;
            long width = maxC[0][n] - minC[0][n] + 1;
            long ans = height * width;
            for (int i = 0; i < n; ++i) {
                ans = Math.min(ans, (Math.max(maxR[0][i], maxR[1][i] - 1) - Math.min(minR[0][i], minR[1][i] - 1) + 1) * width);
                ans = Math.min(ans, (Math.max(maxR[0][i], maxR[1][i] + 1) - Math.min(minR[0][i], minR[1][i] + 1) + 1) * width);
                ans = Math.min(ans, (Math.max(maxC[0][i], maxC[1][i] - 1) - Math.min(minC[0][i], minC[1][i] - 1) + 1) * height);
                ans = Math.min(ans, (Math.max(maxC[0][i], maxC[1][i] + 1) - Math.min(minC[0][i], minC[1][i] + 1) + 1) * height);
            }
            writer.println(ans);
        }

        writer.close();
    }

    private static class SimpleScanner {

        private static final int BUFFER_SIZE = 10240;

        private Readable in;
        private CharBuffer buffer;
        private boolean eof;

        SimpleScanner(InputStream in) {
            this.in = new BufferedReader(new InputStreamReader(in));
            buffer = CharBuffer.allocate(BUFFER_SIZE);
            buffer.limit(0);
            eof = false;
        }

        private char read() {
            if (!buffer.hasRemaining()) {
                buffer.clear();
                int n;
                try {
                    n = in.read(buffer);
                } catch (IOException e) {
                    n = -1;
                }
                if (n <= 0) {
                    eof = true;
                    return '\0';
                }
                buffer.flip();
            }
            return buffer.get();
        }

        void checkEof() {
            if (eof)
                throw new NoSuchElementException();
        }

        char nextChar() {
            checkEof();
            char b = read();
            checkEof();
            return b;
        }

        String next() {
            char b;
            do {
                b = read();
                checkEof();
            } while (Character.isWhitespace(b));
            StringBuilder sb = new StringBuilder();
            do {
                sb.append(b);
                b = read();
            } while (!eof && !Character.isWhitespace(b));
            return sb.toString();
        }

        int nextInt() {
            return Integer.valueOf(next());
        }

        long nextLong() {
            return Long.valueOf(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}


import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;

public class Main {
    void solve() {
        int t=ni();
        while(t-->0){
            char s[]=ns().toCharArray();
            int sz1=0,sz2=0;
            for(int i=0;i<s.length;i++){
                if(s[i]=='A' || s[i]=='D') sz1++;
                else sz2++;
            }
            int a1[]=new int[sz1];
            int a2[]=new int[sz2];
            int i1=0,i2=0;
            for(int i=0;i<s.length;i++){
                if(s[i]=='A') a1[i1++]=-1;
                else if(s[i]=='D') a1[i1++]=1;
                else if(s[i]=='W') a2[i2++]=1;
                else a2[i2++]=-1;
            }
            int ans1[]=find(a1),ans2[]=find(a2);
            long ans=Long.MAX_VALUE;
            ans=Math.min(ans1[0]*1L*ans2[1],ans1[1]*1L*ans2[0]);
            pw.println(ans);
        }
    }
    int [] find(int a[]){
        if(a.length==0) {
            return new int[]{1,1};
        }
        int mx=0,mn=0;
        int c=0;
        for(int i=0;i<a.length;i++){
            c+=a[i];
            mx=Math.max(mx,c);
            mn=Math.min(mn,c);
        }
       // pw.println(mx+" "+mn);
        int ans[]={mx-mn+1,Math.max(2,mx-mn)};

        return ans;
    }
    long M = (long) 1e9 + 7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");

    }

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}


import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;

public class Main {
    void solve() {
        int t=ni();
        while(t-->0){
            char s[]=ns().toCharArray();
            int sz1=0,sz2=0;
            for(int i=0;i<s.length;i++){
                if(s[i]=='A' || s[i]=='D') sz1++;
                else sz2++;
            }
            int a1[]=new int[sz1+1];
            int a2[]=new int[sz2+1];
            int i1=1,i2=1;
            for(int i=0;i<s.length;i++){
                if(s[i]=='A') a1[i1++]=-1;
                else if(s[i]=='D') a1[i1++]=1;
                else if(s[i]=='W') a2[i2++]=1;
                else a2[i2++]=-1;
            }
            int ans1[]=find(a1),ans2[]=find(a2);
            long ans=Long.MAX_VALUE;
            ans=Math.min(ans1[0]*1L*ans2[1],ans1[1]*1L*ans2[0]);
            pw.println(ans);
        }
    }
    int [] find(int a[]){
        if(a.length==1) {
            return new int[]{1,1};
        }
        int mx=0,mn=0;
        int c[]=new int[a.length];
        for(int i=1;i<a.length;i++){
            c[i]=c[i-1]+a[i];
            mx=Math.max(mx,c[i]);
            mn=Math.min(mn,c[i]);
        }

        int ans[]={mx-mn+1,Integer.MAX_VALUE};
        int sufMX[]=new int[a.length+1];
        int sufMN[]=new int[a.length+1];

        int prefMX[]=new int[a.length];
        int prefMN[]=new int[a.length];
        for(int i=a.length-1;i>=1;i--){
            sufMX[i]=sufMN[i]=c[i];
            if(i<a.length-1){
                sufMX[i]=Math.max(sufMX[i],sufMX[i+1]);
                sufMN[i]=Math.min(sufMN[i],sufMN[i+1]);
            }
        }
        for(int i=1;i<a.length;i++){
            prefMX[i]=prefMN[i]=c[i];
            if(i>1){
                prefMX[i]=Math.max(prefMX[i],prefMX[i-1]);
                prefMN[i]=Math.min(prefMN[i],prefMN[i-1]);
            }
        }
        for(int i=1;i<a.length;i++){
            mx=Math.max(prefMX[i-1],Math.max(c[i-1]+1,sufMX[i]+1));
            mn=Math.min(prefMN[i-1],Math.min(c[i-1]+1,sufMN[i]+1));
            ans[1]=Math.min(ans[1],mx-mn+1);
           // pw.println(mx+" "+mn+" "+prefMX[i-1]+" "+sufMX[i-1]);
            mx=Math.max(prefMX[i-1],Math.max(c[i-1]-1,sufMX[i]-1));
            mn=Math.min(prefMN[i-1],Math.min(c[i-1]-1,sufMN[i]-1));
            ans[1]=Math.min(ans[1],mx-mn+1);
         //   pw.println(mx+" "+mn);

        }

     //   pw.println(ans[0]+" "+ans[1]);
        return ans;
    }
    long M = (long) 1e9 + 7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");

    }

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}


import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;

public class Main {
    void solve() {
        int t=ni();
        while(t-->0){
            char s[]=ns().toCharArray();
            int sz1=0,sz2=0;
            for(int i=0;i<s.length;i++){
                if(s[i]=='A' || s[i]=='D') sz1++;
                else sz2++;
            }
            int a1[]=new int[sz1+1];
            int a2[]=new int[sz2+1];
            int i1=1,i2=1;
            for(int i=0;i<s.length;i++){
                if(s[i]=='A') a1[i1++]=-1;
                else if(s[i]=='D') a1[i1++]=1;
                else if(s[i]=='W') a2[i2++]=1;
                else a2[i2++]=-1;
            }
            int ans1[]=find(a1),ans2[]=find(a2);
            long ans=Math.min(ans1[0]*1L*ans2[1],ans1[1]*1L*ans2[0]);
            pw.println(ans);
        }
    }
    int [] find(int a[]){
        if(a.length==1) {
            return new int[]{1,1};
        }
        int mx=0,mn=0;
        int c[]=new int[a.length];
        for(int i=1;i<a.length;i++){
            c[i]=c[i-1]+a[i];
            mx=Math.max(mx,c[i]);
            mn=Math.min(mn,c[i]);
        }

        int ans[]={mx-mn+1,Integer.MAX_VALUE};
        int sufMX[]=new int[a.length+1];
        int sufMN[]=new int[a.length+1];

        int prefMX[]=new int[a.length];
        int prefMN[]=new int[a.length];
        for(int i=a.length-1;i>=1;i--){
            sufMX[i]=sufMN[i]=c[i];
            if(i<a.length-1){
                sufMX[i]=Math.max(sufMX[i],sufMX[i+1]);
                sufMN[i]=Math.min(sufMN[i],sufMN[i+1]);
            }
        }
        for(int i=1;i<a.length;i++){
            prefMX[i]=prefMN[i]=c[i];

                prefMX[i]=Math.max(prefMX[i],prefMX[i-1]);
                prefMN[i]=Math.min(prefMN[i],prefMN[i-1]);

        }
        for(int i=1;i<a.length;i++){
            mx=Math.max(prefMX[i-1],Math.max(c[i-1]+1,sufMX[i]+1));
            mn=Math.min(prefMN[i-1],Math.min(c[i-1]+1,sufMN[i]+1));
            ans[1]=Math.min(ans[1],mx-mn+1);
           // pw.println(mx+" "+mn+" "+prefMX[i-1]+" "+sufMX[i-1]);
            mx=Math.max(prefMX[i-1],Math.max(c[i-1]-1,sufMX[i]-1));
            mn=Math.min(prefMN[i-1],Math.min(c[i-1]-1,sufMN[i]-1));
            ans[1]=Math.min(ans[1],mx-mn+1);
          //  pw.println(mx+" "+mn);
        }

     //   pw.println(ans[0]+" "+ans[1]);
        return ans;
    }
    long M = (long) 1e9 + 7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";

    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");

    }

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if (lenbuf == -1) throw new InputMismatchException();
        if (ptrbuf >= lenbuf) {
            ptrbuf = 0;
            try {
                lenbuf = is.read(inbuf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (lenbuf <= 0) return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) {
        return !(c >= 33 && c <= 126);
    }

    private int skip() {
        int b;
        while ((b = readByte()) != -1 && isSpaceChar(b)) ;
        return b;
    }

    private double nd() {
        return Double.parseDouble(ns());
    }

    private char nc() {
        return (char) skip();
    }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while (p < n && !(isSpaceChar(b))) {
            buf[p++] = (char) b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for (int i = 0; i < n; i++) map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
        if (b == '-') {
            minus = true;
            b = readByte();
        }

        while (true) {
            if (b >= '0' && b <= '9') {
                num = num * 10 + (b - '0');
            } else {
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private void tr(Object... o) {
        if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
    }

}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author svilen.marchev@gmail.com
 */
public class Main {
  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    PrintWriter out = new PrintWriter(outputStream);
    TaskC solver = new TaskC();
    solver.solve(1, in, out);
    out.close();
  }

  static class TaskC {
    static final int[][] OFFSETS = new int[][]{
        // Offsets for row, column. (0,0) is the top left corner.
        new int[]{-1, 0}, // W
        new int[]{+1, 0}, // S
        new int[]{0, -1}, // A
        new int[]{0, +1}, // D
    };

    int[] offsetForMove(char c) {
      switch (c) {
        case 'W':
          return OFFSETS[0];
        case 'S':
          return OFFSETS[1];
        case 'A':
          return OFFSETS[2];
        case 'D':
          return OFFSETS[3];
        default:
          throw new AssertionError();
      }
    }

    char reversePathMove(char c) {
      switch (c) {
        case 'W':
          return 'S';
        case 'S':
          return 'W';
        case 'A':
          return 'D';
        case 'D':
          return 'A';
        default:
          throw new AssertionError();
      }
    }

    String reversePath(String s) {
      StringBuilder sb = new StringBuilder(s);
      sb.reverse();
      for (int i = 0; i < sb.length(); ++i) {
        sb.setCharAt(i, reversePathMove(sb.charAt(i)));
      }
      return sb.toString();
    }

    long tryToAdaptToFit(TaskC.Box reducedBox, TaskC.Point startingPoint, String path) {
      TaskC.Point point = startingPoint;
      TaskC.Box box = new TaskC.Box(point, point);
      if (!reducedBox.contains(point)) {
        return -1;
      }

      boolean hasCorrected = false;
      for (int i = 0; i < path.length(); ++i) {
        int[] off = offsetForMove(path.charAt(i));
        TaskC.Point newPoint = new TaskC.Point(point.r + off[0], point.c + off[1]);
        if (!hasCorrected && !reducedBox.contains(newPoint)) {
          hasCorrected = true;
          // Push an immediate contra-move of this move, so that we stay in the reduced box.
          // We do this simply by ignoring this move, but we need to update the box to
          // account for the extra move.
          int[] contraOff = offsetForMove(reversePathMove(path.charAt(i)));
          TaskC.Point contraPoint = new TaskC.Point(point.r + contraOff[0], point.c + contraOff[1]);
          box = TaskC.Box.copyUpdate(box, contraPoint);
        } else {
          point = newPoint;
          box = TaskC.Box.copyUpdate(box, point);
        }
      }

      return box.area();
    }

    long calcMinReducedArea(String path) {
      // boxFromMove[0] - the bounding box of the whole path, including the point before
      // following any move.
      // boxFromMove[i] - the bounding box from the (i-1)th move on, with the (i-1)th move
      // already done.
      TaskC.Box[] boxFromMove = new TaskC.Box[path.length() + 1];

      String reversedPath = reversePath(path);

      TaskC.Point point = new TaskC.Point(0, 0);
      TaskC.Box box = new TaskC.Box(point, point);
      boxFromMove[path.length()] = box;

      for (int i = 0; i < reversedPath.length(); ++i) {
        int[] off = offsetForMove(reversedPath.charAt(i));
        point = new TaskC.Point(point.r + off[0], point.c + off[1]);
        box = TaskC.Box.copyUpdate(box, point);
        boxFromMove[path.length() - 1 - i] = box;
      }

      System.out.println(box);
      System.out.println(box.area());

      TaskC.Box wholeBox = box;
      TaskC.Point startingPoint = point;

      long minArea = wholeBox.area();

      {
        TaskC.Box withoutFirstCol = new TaskC.Box(new TaskC.Point(wholeBox.tl.r, wholeBox.tl.c + 1),
            wholeBox.br);
        long area = tryToAdaptToFit(withoutFirstCol, startingPoint, path);
//      System.out.println("area=" + area);
        if (area != -1) {
          minArea = Math.min(minArea, area);
        }
      }

      {
        TaskC.Box withoutFirstRow = new TaskC.Box(new TaskC.Point(wholeBox.tl.r + 1, wholeBox.tl.c),
            wholeBox.br);
        long area = tryToAdaptToFit(withoutFirstRow, startingPoint, path);
        if (area != -1) {
          minArea = Math.min(minArea, area);
        }
      }

      {
        TaskC.Box withoutLastRow = new TaskC.Box(wholeBox.tl,
            new TaskC.Point(wholeBox.br.r - 1, wholeBox.br.c));
        long area = tryToAdaptToFit(withoutLastRow, startingPoint, path);
        if (area != -1) {
          minArea = Math.min(minArea, area);
        }
      }

      {
        TaskC.Box withoutLastCol = new TaskC.Box(wholeBox.tl,
            new TaskC.Point(wholeBox.br.r, wholeBox.br.c - 1));
        long area = tryToAdaptToFit(withoutLastCol, startingPoint, path);
        if (area != -1) {
          minArea = Math.min(minArea, area);
        }
      }

      return minArea;
    }

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      int tests = in.readInt();
      for (int test = 0; test < tests; ++test) {
        String path = in.readString();
        out.println(calcMinReducedArea(path));
      }
    }

    static class Point {
      final int r;
      final int c;

      Point(int r, int c) {
        this.r = r;
        this.c = c;
      }

      public String toString() {
        return String.format("(%d,%d)", r, c);
      }

    }

    static class Box {
      final TaskC.Point tl;
      final TaskC.Point br;

      Box(TaskC.Point tl, TaskC.Point br) {
        this.tl = tl;
        this.br = br;
      }

      long area() {
        return ((long) br.r - tl.r + 1) * (br.c - tl.c + 1);
      }

      public String toString() {
        return String.format("%s-%s", tl, br);
      }

      boolean contains(TaskC.Point point) {
        return tl.r <= point.r && point.r <= br.r &&
            tl.c <= point.c && point.c <= br.c;
      }

      static TaskC.Box copyUpdate(TaskC.Box existing, TaskC.Point point) {
        return new TaskC.Box(
            new TaskC.Point(Math.min(existing.tl.r, point.r), Math.min(existing.tl.c, point.c)),
            new TaskC.Point(Math.max(existing.br.r, point.r), Math.max(existing.br.c, point.c)));
      }

    }

  }

  static class InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private InputReader.SpaceCharFilter filter;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (numChars == -1) {
        throw new InputMismatchException();
      }
      if (curChar >= numChars) {
        curChar = 0;
        try {
          numChars = stream.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (numChars <= 0) {
          return -1;
        }
      }
      return buf[curChar++];
    }

    public int readInt() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = read();
      }
      int res = 0;
      do {
        if (c < '0' || c > '9') {
          throw new InputMismatchException();
        }
        res *= 10;
        res += c - '0';
        c = read();
      } while (!isSpaceChar(c));
      return res * sgn;
    }

    public String readString() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      StringBuilder res = new StringBuilder();
      do {
        if (Character.isValidCodePoint(c)) {
          res.appendCodePoint(c);
        }
        c = read();
      } while (!isSpaceChar(c));
      return res.toString();
    }

    public boolean isSpaceChar(int c) {
      if (filter != null) {
        return filter.isSpaceChar(c);
      }
      return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
      public boolean isSpaceChar(int ch);

    }

  }
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in Actual solution is at the top
 *
 * @author svilen.marchev@gmail.com
 */
public class Main {
  public static void main(String[] args) {
    InputStream inputStream = System.in;
    OutputStream outputStream = System.out;
    InputReader in = new InputReader(inputStream);
    PrintWriter out = new PrintWriter(outputStream);
    TaskC solver = new TaskC();
    solver.solve(1, in, out);
    out.close();
  }

  static class TaskC {
    static final int[][] OFFSETS = new int[][]{
        // Offsets for row, column. (0,0) is the top left corner.
        new int[]{-1, 0}, // W
        new int[]{+1, 0}, // S
        new int[]{0, -1}, // A
        new int[]{0, +1}, // D
    };

    int[] offsetForMove(char c) {
      switch (c) {
        case 'W':
          return OFFSETS[0];
        case 'S':
          return OFFSETS[1];
        case 'A':
          return OFFSETS[2];
        case 'D':
          return OFFSETS[3];
        default:
          throw new AssertionError();
      }
    }

    char reversePathMove(char c) {
      switch (c) {
        case 'W':
          return 'S';
        case 'S':
          return 'W';
        case 'A':
          return 'D';
        case 'D':
          return 'A';
        default:
          throw new AssertionError();
      }
    }

    String reversePath(String s) {
      StringBuilder sb = new StringBuilder(s);
      sb.reverse();
      for (int i = 0; i < sb.length(); ++i) {
        sb.setCharAt(i, reversePathMove(sb.charAt(i)));
      }
      return sb.toString();
    }

    long tryToAdaptToFit(TaskC.Box reducedBox, TaskC.Point startingPoint, String path) {
      TaskC.Point point = startingPoint;
      TaskC.Box box = new TaskC.Box(point, point);
      if (!reducedBox.contains(point)) {
        return -1;
      }

      boolean hasCorrected = false;
      for (int i = 0; i < path.length(); ++i) {
        int[] off = offsetForMove(path.charAt(i));
        TaskC.Point newPoint = new TaskC.Point(point.r + off[0], point.c + off[1]);
        if (!hasCorrected && !reducedBox.contains(newPoint)) {
          hasCorrected = true;
          // Push an immediate contra-move of this move, so that we stay in the reduced box.
          // We do this simply by ignoring this move, but we need to update the box to
          // account for the extra move.
          int[] contraOff = offsetForMove(reversePathMove(path.charAt(i)));
          TaskC.Point contraPoint = new TaskC.Point(point.r + contraOff[0], point.c + contraOff[1]);
          box = TaskC.Box.copyUpdate(box, contraPoint);
        } else {
          point = newPoint;
          box = TaskC.Box.copyUpdate(box, point);
        }
      }

      return box.area();
    }

    long calcMinReducedArea(String path) {
      // boxFromMove[0] - the bounding box of the whole path, including the point before
      // following any move.
      // boxFromMove[i] - the bounding box from the (i-1)th move on, with the (i-1)th move
      // already done.
      TaskC.Box[] boxFromMove = new TaskC.Box[path.length() + 1];

      String reversedPath = reversePath(path);

      TaskC.Point point = new TaskC.Point(0, 0);
      TaskC.Box box = new TaskC.Box(point, point);
      boxFromMove[path.length()] = box;

      for (int i = 0; i < reversedPath.length(); ++i) {
        int[] off = offsetForMove(reversedPath.charAt(i));
        point = new TaskC.Point(point.r + off[0], point.c + off[1]);
        box = TaskC.Box.copyUpdate(box, point);
        boxFromMove[path.length() - 1 - i] = box;
      }

//    System.out.println(box);
//    System.out.println(box.area());

      TaskC.Box wholeBox = box;
      TaskC.Point startingPoint = point;

      long minArea = wholeBox.area();

      {
        TaskC.Box withoutCol0 = new TaskC.Box(new TaskC.Point(0, 1), wholeBox.br);
        long area = tryToAdaptToFit(withoutCol0, startingPoint, path);
//      System.out.println("area=" + area);
        if (area != -1) {
          minArea = Math.min(minArea, area);
        }
      }

      {
        TaskC.Box withoutRow0 = new TaskC.Box(new TaskC.Point(1, 0), wholeBox.br);
        long area = tryToAdaptToFit(withoutRow0, startingPoint, path);
        if (area != -1) {
          minArea = Math.min(minArea, area);
        }
      }

      {
        TaskC.Box withoutLastRow = new TaskC.Box(wholeBox.tl,
            new TaskC.Point(wholeBox.br.r - 1, wholeBox.br.c));
        long area = tryToAdaptToFit(withoutLastRow, startingPoint, path);
        if (area != -1) {
          minArea = Math.min(minArea, area);
        }
      }

      {
        TaskC.Box withoutLastCol = new TaskC.Box(wholeBox.tl,
            new TaskC.Point(wholeBox.br.r, wholeBox.br.c - 1));
        long area = tryToAdaptToFit(withoutLastCol, startingPoint, path);
        if (area != -1) {
          minArea = Math.min(minArea, area);
        }
      }

      return minArea;
    }

    public void solve(int testNumber, InputReader in, PrintWriter out) {
      int tests = in.readInt();
      for (int test = 0; test < tests; ++test) {
        String path = in.readString();
        out.println(calcMinReducedArea(path));
      }
    }

    static class Point {
      final int r;
      final int c;

      Point(int r, int c) {
        this.r = r;
        this.c = c;
      }

      public String toString() {
        return String.format("(%d,%d)", r, c);
      }

    }

    static class Box {
      final TaskC.Point tl;
      final TaskC.Point br;

      Box(TaskC.Point tl, TaskC.Point br) {
        this.tl = tl;
        this.br = br;
      }

      long area() {
        return ((long) br.r - tl.r + 1) * (br.c - tl.c + 1);
      }

      public String toString() {
        return String.format("%s-%s", tl, br);
      }

      boolean contains(TaskC.Point point) {
        return tl.r <= point.r && point.r <= br.r &&
            tl.c <= point.c && point.c <= br.c;
      }

      static TaskC.Box copyUpdate(TaskC.Box existing, TaskC.Point point) {
        return new TaskC.Box(
            new TaskC.Point(Math.min(existing.tl.r, point.r), Math.min(existing.tl.c, point.c)),
            new TaskC.Point(Math.max(existing.br.r, point.r), Math.max(existing.br.c, point.c)));
      }

    }

  }

  static class InputReader {
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private InputReader.SpaceCharFilter filter;

    public InputReader(InputStream stream) {
      this.stream = stream;
    }

    public int read() {
      if (numChars == -1) {
        throw new InputMismatchException();
      }
      if (curChar >= numChars) {
        curChar = 0;
        try {
          numChars = stream.read(buf);
        } catch (IOException e) {
          throw new InputMismatchException();
        }
        if (numChars <= 0) {
          return -1;
        }
      }
      return buf[curChar++];
    }

    public int readInt() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      int sgn = 1;
      if (c == '-') {
        sgn = -1;
        c = read();
      }
      int res = 0;
      do {
        if (c < '0' || c > '9') {
          throw new InputMismatchException();
        }
        res *= 10;
        res += c - '0';
        c = read();
      } while (!isSpaceChar(c));
      return res * sgn;
    }

    public String readString() {
      int c = read();
      while (isSpaceChar(c)) {
        c = read();
      }
      StringBuilder res = new StringBuilder();
      do {
        if (Character.isValidCodePoint(c)) {
          res.appendCodePoint(c);
        }
        c = read();
      } while (!isSpaceChar(c));
      return res.toString();
    }

    public boolean isSpaceChar(int c) {
      if (filter != null) {
        return filter.isSpaceChar(c);
      }
      return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
      return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
      public boolean isSpaceChar(int ch);

    }

  }
}