#include <bits/stdc++.h>
using namespace std;
const int MaxC = 256;
const int MAX = 100020;
int offset, n;
int suma[MAX], tmp[MAX];
int rank1[MAX], rank2[MAX];
int c[MAX], p[MAX], lcp[MAX];
bool different(int a, int b) {
  if (b + offset >= n) return true;
  if (rank1[a] != rank1[b]) return true;
  if (rank2[a] != rank2[b]) return true;
  return false;
}
void suffix_array(string &text) {
  n = text.size();
  for (int i = 0; i < MaxC; i++) suma[i] = 0;
  for (int i = 0; i < n; i++) suma[text[i]]++;
  for (int i = 0; i < MaxC; i++) suma[i + 1] += suma[i];
  for (int i = 0; i < n; i++) c[i] = suma[text[i]] - 1;
  for (offset = 1; offset <= n; offset <<= 1) {
    for (int i = 0; i < n; i++) {
      rank1[i] = c[i];
      rank2[i] = (i + offset < n) ? c[i + offset] : 0;
    }
    fill(suma, suma + n, 0);
    for (int i = 0; i < n; i++) suma[rank2[i]]++;
    for (int i = 0; i < n; i++) suma[i + 1] += suma[i];
    for (int i = 0; i < n; i++) tmp[--suma[rank2[i]]] = i;
    fill(suma, suma + n, 0);
    for (int i = 0; i < n; i++) suma[rank1[i]]++;
    for (int i = 0; i < n; i++) suma[i + 1] += suma[i];
    for (int i = n - 1; i >= 0; i--) p[--suma[rank1[tmp[i]]]] = tmp[i];
    c[p[0]] = 0;
    for (int i = 1; i < n; i++) {
      c[p[i]] = c[p[i - 1]];
      if (different(p[i], p[i - 1])) c[p[i]]++;
    }
  }
  offset = 0;
  for (int i = 0; i < n; i++) {
    if (c[i] == n - 1) {
      lcp[n - 1] = 0;
      continue;
    }
    while (text[i + offset] == text[p[c[i] + 1] + offset] &&
           text[i + offset] != '{')
      offset++;
    lcp[c[i]] = offset;
    if (offset > 0) offset--;
  }
}
void clear() {
  offset = n = 0;
  for (int i = 0; i < MAX; i++) {
    suma[i] = tmp[i] = rank1[i] = rank2[i] = c[i] = p[i] = lcp[i] = 0;
  }
}
long long x[MAX], x2[MAX];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int T;
  cin >> T;
  while (T--) {
    clear();
    string s;
    cin >> s;
    suffix_array(s);
    stack<int> st;
    x[n - 1] = 0;
    x2[n - 1] = 0;
    st.push(n - 1);
    for (int i = n - 2; i >= 0; i--) {
      while (!st.empty() && lcp[i] <= lcp[st.top()]) {
        st.pop();
      }
      int j = 0;
      if (st.empty()) {
        j = n - 1;
      } else {
        j = st.top();
      }
      x[i] = x[j] + (long long)lcp[i] * (long long)(j - i) + lcp[i] - lcp[j];
      x2[i] = x2[j] + 2ll * (j - i) * x[j] +
              (long long)(j - i) * (j - i) * lcp[j] +
              (long long)(j - i + 1) * (j - i + 1) * (lcp[i] - lcp[j]);
      st.push(i);
    }
    long long sol = n - p[0] - lcp[0] + x2[0];
    for (int i = 1; i < n; i++) {
      sol += n - p[i] - max(lcp[i - 1], lcp[i]);
      if (lcp[i - 1] >= lcp[i]) {
        continue;
      }
      sol += x2[i];
      sol -= x2[i - 1] - 2LL * x[i - 1] + lcp[i - 1];
    }
    cout << sol << '\n';
  }
}
