#include <bits/stdc++.h>
using namespace std;
string s;
int sa[100005], sa_rank[100005], tmp[100005], lcp[100005];
int gap;
bool sa_cmp(int x, int y) {
  if (sa_rank[x] != sa_rank[y]) return sa_rank[x] < sa_rank[y];
  x += gap;
  y += gap;
  return x < s.size() && y < s.size() ? sa_rank[x] < sa_rank[y] : x > y;
}
void build_sa() {
  for (int i = 0; i < s.size(); i++) sa[i] = i, sa_rank[i] = s[i];
  for (gap = 1;; gap *= 2) {
    sort(sa, sa + s.size(), sa_cmp);
    for (int i = 0; i < s.size(); i++)
      tmp[i + 1] = tmp[i] + sa_cmp(sa[i], sa[i + 1]);
    for (int i = 0; i < s.size(); i++) sa_rank[sa[i]] = tmp[i];
    if (tmp[s.size() - 1] == s.size() - 1) break;
  }
}
void build_lcp() {
  int k = 0;
  for (int i = 0; i < s.size(); i++) {
    if (sa_rank[i] != s.size() - 1) {
      for (int j = sa[sa_rank[i] + 1]; s[i + k] == s[j + k];) ++k;
      lcp[sa_rank[i]] = k;
      if (k) k--;
    }
  }
}
int test;
vector<int> st;
int main() {
  iostream::sync_with_stdio(0);
  cin >> test;
  while (test--) {
    memset(sa, 0, sizeof(sa));
    memset(sa_rank, 0, sizeof(sa_rank));
    memset(tmp, 0, sizeof(tmp));
    memset(lcp, 0, sizeof(lcp));
    st.clear();
    cin >> s;
    st.push_back(s.size());
    long long ans = 0;
    build_sa();
    build_lcp();
    int m = (int)s.size();
    for (int i = 0; i < s.size(); i++) {
      int last = -1;
      while (lcp[st.back()] > lcp[i]) {
        ans += 1ll * (i + 1 - st.back() % m) * (i + 1 - st.back() % m) *
               (lcp[st.back()] - max(lcp[i], lcp[st[st.size() - 2]]));
        last = st.back();
        st.pop_back();
      }
      ans += (m - sa[i]) - max(lcp[i], lcp[max(0, i - 1)]);
      assert(last != m);
      if (last != -1 && lcp[i] != lcp[st.back()]) {
        lcp[last] = lcp[i];
        st.push_back(last);
      } else if (lcp[i] != lcp[st.back()])
        st.push_back(i);
    }
    assert(st.size() == 1);
    cout << ans << endl;
  }
}
