/+ dub.sdl:
    name "I"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv, std.traits;
// import dcomp.foundation, dcomp.scanner;
// import dcomp.array;
// import dcomp.algorithm;
// import dcomp.string;

/// 遅延伝搬Segment Tree
struct LazySeg(T, L, alias opTT, alias opTL, alias opLL, T eT, L eL) {
    const int n, sz, lg;
    T[] d;
    L[] lz;
    @disable this();
    this(int n) {
        import std.algorithm : fill, each;
        import core.bitop : bsr;
        if (n == 0) return;
        int lg = n.bsr;
        if ((2^^lg) < n) lg++;
        this.n = n;
        this.sz = 2^^lg;
        this.lg = lg;
        d = new T[](2*this.sz);
        d.each!((ref x) => x = eT);
        lz = new L[](2*this.sz);
        lz.each!((ref x) => x = eL);
    }
    private void lzAdd(int k, L x) {
        d[k] = opTL(d[k], x);
        lz[k] = opLL(lz[k], x);
    }
    private void push(int k) {
        if (lz[k] == eL) return;
        lzAdd(2*k, lz[k]);
        lzAdd(2*k+1, lz[k]);
        lz[k] = eL;
    }
    //d[a]+d[a+1]+...+d[b-1]
    T sum(int a, int b, int l, int r, int k) {
        if (b <= l || r <= a) return eT;
        if (a <= l && r <= b) return d[k];
        push(k);
        int md = (l+r)/2;
        return opTT(sum(a, b, l, md, 2*k),
            sum(a, b, md, r, 2*k+1));
    }
    T single(int k) {
        k += sz;
        foreach_reverse (int i; 1..lg+1) {
            push(k>>i);
        }
        return d[k];
    }
    void singleSet(T x, int k) {
        k += sz;
        foreach_reverse (int i; 1..lg+1) {
            push(k>>i);
        }
        d[k] = x;
        foreach (int i; 1..lg+1) {
            d[k>>i] = opTT(d[2*(k>>i)], d[2*(k>>i)+1]);
        }
    }
    T sum(int a, int b) {
        assert(0 <= a && a <= b && b <= n);
        return sum(a, b, 0, sz, 1);
    }
    void add(int a, int b, L x, int l, int r, int k) {
        if (b <= l || r <= a) return;
        if (a <= l && r <= b) {
            lzAdd(k, x);
            return;
        }
        push(k);
        int md = (l+r)/2;
        add(a, b, x, l, md, 2*k);
        add(a, b, x, md, r, 2*k+1);
        d[k] = opTT(d[2*k], d[2*k+1]);
    }
    void add(int a, int b, L x) {
        assert(0 <= a && a <= b && b <= n);
        add(a, b, x, 0, sz, 1);
    }
    @property int opDollar() const {return sz;}
    struct Range {
        LazySeg* seg;
        int start, end;
        @property T sum() {
            return seg.sum(start, end);
        }
    }
    T opIndex(int k) {
        assert(0 <= k && k < n);
        return single(k);
    }
    void opIndexAssign(T x, int k) {
        assert(0 <= k && k < n);
        singleSet(x, k);
    }
    int[2] opSlice(size_t dim)(int start, int end) {
        assert(0 <= start && start <= end && end <= sz);
        return [start, end];
    }
    Range opIndex(int[2] rng) {
        return Range(&this, rng[0], rng[1]);
    }
    void opIndexOpAssign(string op : "+")(L x, int[2] rng) {
        add(rng[0], rng[1], x);
    }
}

int binSearchLeft(alias pred, TR)(TR t, int a, int b)
if (isInstanceOf!(LazySeg, TR)) {
    alias args = TemplateArgsOf!TR;
    alias opTT = args[2];
    with (t) {
        auto x = args[5];
        if (pred(x)) return a-1;
        int pos = a;
        void f(int a, int b, int l, int r, int k) {
            if (b <= l || r <= a) return;
            if (a <= l && r <= b && !pred(opTT(x, d[k]))) {
                x = opTT(x, d[k]);
                pos = r;
                return;
            }
            if (l+1 == r) return;
            push(k);
            int md = (l+r)/2;
            f(a, b, l, md, 2*k);
            if (pos >= md) f(a, b, md, r, 2*k+1);
        }
        f(a, b, 0, sz, 1);
        return pos;
    }
}

void solve() {
    string s;
    sc.read(s);
    auto saInfo = suffixArray(s);
    int n = s.length.to!int;
    import std.typecons;
    alias T = Tuple!(long, int, int);
    auto tr = LazySeg!(T, int,
        (a, b)=>T(a[0]+b[0], a[1]+b[1], max(a[2], b[2])),
        (a, b)=>T(long(b) * a[1], a[1], b),
        (a, b)=>b,
        T(0L, 1, -(10^^9)), -1)(n);
    tr[0..n] += 10^^9;
    long sm = 0;
    foreach (i; 1..n) {
        auto u = saInfo.lcp[i];
        auto le = tr.binSearchLeft!(x => x[2] >= u)(0, i);
        tr[le..i] += u;
        sm += tr[0..i].sum[0];
//        writeln(tr);
    }
    writeln(sm*2 + long(n)*(n+1)/2);
}

int main() {
    int n;
    sc.read(n);
    foreach (i; 0..n) {
        solve();
    }
    return 0;
}

Scanner sc;
static this() {
    sc = new Scanner(stdin);
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/array.d */
// module dcomp.array;

T[N] fixed(T, size_t N)(T[N] a) {return a;}

struct FastAppender(A) {
    import std.algorithm : max;
    import std.range.primitives : ElementEncodingType;
    import core.stdc.string : memcpy;

    private alias T = ElementEncodingType!A;
    private T* _data;
    private size_t len, cap;

    @property size_t length() {return len;}

    void reserve(size_t nlen) {
        import core.memory : GC;
        if (nlen <= cap) return;

        void* nx = GC.malloc(nlen * T.sizeof);

        cap = nlen;
        if (len) memcpy(nx, _data, len * T.sizeof);
        _data = cast(T*)(nx);
    }

    void opOpAssign(string op : "~")(T item) {
        if (len == cap) {
            reserve(max(4, cap*2));
        }
        _data[len++] = item;
    }

    void clear() {
        len = 0;
    }

    T[] data() {
        return (_data) ? _data[0..len] : null;
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/string.d */
// module dcomp.string;

struct SA(T) {
    T[] s;

    int[] sa, rsa, lcp;
    this(in T[] s) {
        size_t n = s.length;
        this.s = s.dup;
        sa = new int[](n+1);
        rsa = new int[](n+1);
        lcp = new int[](n);
    }
}

int[] sais(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm, std.range;
    int n = _s.length.to!int;
    int[] sa = new int[](n+1);
    if (n == 0) return sa;

    auto s = _s.map!"a+1".array ~ T(0); B++;

    bool[] ls = new bool[](n+1);
    ls[n] = true;
    foreach_reverse (i; 0..n) {
        ls[i] = (s[i] == s[i+1]) ? ls[i+1] : (s[i] < s[i+1]);
    }

    int[] sumL = new int[](B+1), sumS = new int[](B+1);
    s.each!((i, c) => !ls[i] ? sumS[c]++ : sumL[c+1]++);
    foreach (i; 0..B) {
        sumL[i+1] += sumS[i];
        sumS[i+1] += sumL[i+1];
    }

    void induce(in int[] lms) {
        sa[] = -1;
        auto buf0 = sumS.dup;
        foreach (d; lms) {
            sa[buf0[s[d]]++] = d;
        }
        auto buf1 = sumL.dup;
        foreach (v; sa) {
            if (v >= 1 && !ls[v-1]) {
                sa[buf1[s[v-1]]++] = v-1;
            }
        }
        auto buf2 = sumL.dup;
        foreach_reverse (v; sa) {
            if (v >= 1 && ls[v-1]) {
                sa[--buf2[s[v-1]+1]] = v-1;
            }
        }
    }

    int[] lms = iota(1, n+1).filter!(i => !ls[i-1] && ls[i]).array;
    int[] lmsMap = new int[](n+1);
    lmsMap[] = -1; lms.each!((i, v) => lmsMap[v] = i.to!int);

    induce(lms);

    if (lms.length >= 2) {
        int m = lms.length.to!int - 1;

        auto lms2 = sa.filter!(v => lmsMap[v] != -1).array;
        int recN = 1;
        int[] recS = new int[](m);
        recS[lmsMap[lms2[1]]] = 1;
        foreach (i; 2..m+1) {
            int l = lms2[i-1], r = lms2[i];
            int nl = lms[lmsMap[l]+1], nr = lms[lmsMap[r]+1];
            if (cmp(s[l..nl+1], s[r..nr+1])) recN++;
            recS[lmsMap[lms2[i]]] = recN;
        }

        induce(lms.indexed(sais!int(recS, recN)).array);
    }

    return sa;
}

SA!T suffixArray(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm;
    int n = _s.length.to!int;
    auto saInfo = SA!T(_s);
    if (n == 0) return saInfo;

    with (saInfo) {
        sa = sais(_s, B);

        sa.each!((i, v) => rsa[v] = i.to!int);

        int h = 0;
        foreach (i; 0..n) {
            int j = sa[rsa[i]-1];
            if (h > 0) h--;
            for (; j+h < n && i+h < n; h++) {
                if (s[j+h] != s[i+h]) break;
            }
            lcp[rsa[i]-1] = h;
        }
    }
    return saInfo;
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/algorithm.d */
// module dcomp.algorithm;

import std.range.primitives;
import std.traits : isFloatingPoint, isIntegral;

T binSearch(alias pred, T)(T l, T r) if (isIntegral!T) {
    while (r-l > 1) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

T binSearch(alias pred, T)(T l, T r, int cnt = 60) if (isFloatingPoint!T) {
    foreach (i; 0..cnt) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

E minimum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? a : b)(seed, range);
}

ElementType!Range minimum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return minimum!pred(range, e);
}

E maximum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? b : a)(seed, range);
}

ElementType!Range maximum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return maximum!pred(range, e);
}

Rotator!Range rotator(Range)(Range r) {
    return Rotator!Range(r);
}

struct Rotator(Range)
if (isForwardRange!Range && hasLength!Range) {
    size_t cnt;
    Range start, now;
    this(Range r) {
        cnt = 0;
        start = r.save;
        now = r.save;
    }
    this(this) {
        start = start.save;
        now = now.save;
    }
    @property bool empty() {
        return now.empty;
    }
    @property auto front() {
        assert(!now.empty);
        import std.range : take, chain;
        return chain(now, start.take(cnt));
    }
    @property Rotator!Range save() {
        return this;
    }
    void popFront() {
        cnt++;
        now.popFront;
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/ascii.d */
// module dcomp.ascii;

struct ASCIIString {
    string s;
    alias s this;
    this(string s) {
        this.s = s;
    }
    ref immutable(char) front() const {
        return s[0];
    }
    void popFront() {
        s = s[1..$];
    }
    ref immutable(char) back() const {
        return s[$-1];
    }
    void popBack() {
        s = s[0..$-1];
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    import core.bitop : bsf, bsr, popcnt;
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}

/+ dub.sdl:
    name "I"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner;
// import dcomp.array;
// import dcomp.algorithm;
// import dcomp.string;
// import dcomp.datastructure.lazyseg;
// import dcomp.container.deque;

void solve() {
    string s;
    sc.read(s);
    auto saInfo = suffixArray(s);
    int n = s.length.to!int;
    auto tr = LazySeg!(long[2], int, (a, b)=>[a[0]+b[0], a[1]+b[1]].fixed, (a, b)=>[b * a[1], a[1]].fixed, (a, b)=>b, [0L, 1L].fixed, -1)(n);
    tr[0..n] += 10^^9;
    long sm = 0;
    Deque!(int[2]) deq;
    deq.insertBack([-1, 0]);
    foreach (i; 1..n) {
        auto u = saInfo.lcp[i];
        while (deq.back[0] >= u) deq.removeBack;
//        auto le = binSearch!(x => tr.single(x)[0] >= u)(-1, i);
        auto le = deq.back[1];
//        writeln(le, " ", le2, " ", deq);
        tr[le..i] += u;
        sm += tr[0..i].sum[0];
        deq.insertBack([u, i]);
//        writeln(tr);
    }
    writeln(sm*2 + long(n)*(n+1)/2);
}

int main() {
    int n;
    sc.read(n);
    foreach (i; 0..n) {
        solve();
    }
    return 0;
}

Scanner sc;
static this() {
    sc = new Scanner(stdin);
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/container/deque.d */
// module dcomp.container.deque;

struct Deque(T, bool mayNull = true) {
    import core.exception : RangeError;
    import core.memory : GC;
    import std.range : ElementType, isInputRange;
    import std.traits : isImplicitlyConvertible;

    struct Payload {
        T *d;
        size_t st, length, cap;
        @property bool empty() const { return length == 0; }
        alias opDollar = length;
        ref inout(T) opIndex(size_t i) inout {
            version(assert) if (length <= i) throw new RangeError();
            return d[(st+i >= cap) ? (st+i-cap) : st+i];
        }
        private void expand() {
            import std.algorithm : max;
            assert(length == cap);
            auto nc = max(size_t(4), 2*cap);
            T* nd = cast(T*)GC.malloc(nc * T.sizeof);
            foreach (i; 0..length) {
                nd[i] = this[i];
            }
            d = nd; st = 0; cap = nc;
        }
        void clear() {
            st = length = 0;
        }
        void insertFront(T v) {
            if (length == cap) expand();
            if (st == 0) st += cap;
            st--; length++;
            this[0] = v;
        }
        void insertBack(T v) {
            if (length == cap) expand();
            length++;
            this[length-1] = v;
        }
        void removeFront() {
            assert(!empty, "Deque.removeFront: Deque is empty");
            st++; length--;
            if (st == cap) st = 0;
        }
        void removeBack() {
            assert(!empty, "Deque.removeBack: Deque is empty");
            length--;
        }
    }
    struct RangeT(A) {
        alias T = typeof(*(A.p));
        alias E = typeof(A.p.d[0]);
        T *p;
        size_t a, b;
        @property bool empty() const { return b <= a; }
        @property size_t length() const { return b-a; }
        @property RangeT save() { return RangeT(p, a, b); }
        @property RangeT!(const A) save() const {
            return typeof(return)(p, a, b);
        }
        alias opDollar = length;
        @property ref inout(E) front() inout { return (*p)[a]; }
        @property ref inout(E) back() inout { return (*p)[b-1]; }
        void popFront() {
            version(assert) if (empty) throw new RangeError();
            a++;
        }
        void popBack() {
            version(assert) if (empty) throw new RangeError();
            b--;
        }
        ref inout(E) opIndex(size_t i) inout { return (*p)[i]; }
        RangeT opSlice() { return this.save; }
        RangeT opSlice(size_t i, size_t j) {
            version(assert) if (i > j || a + j > b) throw new RangeError();
            return typeof(return)(p, a+i, a+j);
        }
        RangeT!(const A) opSlice() const { return this.save; }
        RangeT!(const A) opSlice(size_t i, size_t j) const {
            version(assert) if (i > j || a + j > b) throw new RangeError();
            return typeof(return)(p, a+i, a+j);
        }
    }

    alias Range = RangeT!Deque;
    alias ConstRange = RangeT!(const Deque);
    alias ImmutableRange = RangeT!(immutable Deque);

    Payload* p;
    private void I() { if (mayNull && !p) p = new Payload(); }
    private void C() const {
        version(assert) if (mayNull && !p) throw new RangeError();
    }
    static if (!mayNull) {
        @disable this();
    }

    private this(Payload* p) {
        this.p = p;
    }
    this(U)(U[] values...) if (isImplicitlyConvertible!(U, T)) {
        p = new Payload();
        foreach (v; values) {
            insertBack(v);
        }
    }

    this(Range)(Range r)
    if (isInputRange!Range &&
    isImplicitlyConvertible!(ElementType!Range, T) &&
    !is(Range == T[])) {
        p = new Payload();
        foreach (v; r) {
            insertBack(v);
        }
    }
    static Deque make() { return Deque(new Payload()); }
    @property bool havePayload() const { return (!mayNull || p); }
    @property bool empty() const { return (!havePayload || p.empty); }
    @property size_t length() const { return (havePayload ? p.length : 0); }
    alias opDollar = length;
    ref inout(T) opIndex(size_t i) inout {C; return (*p)[i]; }
    ref inout(T) front() inout {C; return (*p)[0]; }
    ref inout(T) back() inout {C; return (*p)[$-1]; }
    void clear() { if (p) p.clear(); }
    void insertFront(T v) {I; p.insertFront(v); }
    void insertBack(T v) {I; p.insertBack(v); }
    void removeFront() {C; p.removeFront(); }
    void removeBack() {C; p.removeBack(); }
    Range opSlice() {I; return Range(p, 0, length); }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/array.d */
// module dcomp.array;

T[N] fixed(T, size_t N)(T[N] a) {return a;}

struct FastAppender(A) {
    import std.algorithm : max;
    import std.range.primitives : ElementEncodingType;
    import core.stdc.string : memcpy;

    private alias T = ElementEncodingType!A;
    private T* _data;
    private size_t len, cap;

    @property size_t length() {return len;}

    void reserve(size_t nlen) {
        import core.memory : GC;
        if (nlen <= cap) return;

        void* nx = GC.malloc(nlen * T.sizeof);

        cap = nlen;
        if (len) memcpy(nx, _data, len * T.sizeof);
        _data = cast(T*)(nx);
    }

    void opOpAssign(string op : "~")(T item) {
        if (len == cap) {
            reserve(max(4, cap*2));
        }
        _data[len++] = item;
    }

    void clear() {
        len = 0;
    }

    T[] data() {
        return (_data) ? _data[0..len] : null;
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/datastructure/lazyseg.d */
// module dcomp.datastructure.lazyseg;

struct LazySeg(T, L, alias opTT, alias opTL, alias opLL, T eT, L eL) {
    const int n, sz, lg;
    T[] d;
    L[] lz;
    @disable this();
    this(int n) {
        import std.algorithm : fill, each;
        import core.bitop : bsr;
        if (n == 0) return;
        int lg = n.bsr;
        if ((2^^lg) < n) lg++;
        this.n = n;
        this.sz = 2^^lg;
        this.lg = lg;
        d = new T[](2*this.sz);
        d.each!((ref x) => x = eT);
        lz = new L[](2*this.sz);
        lz.each!((ref x) => x = eL);
    }
    private void lzAdd(int k, L x) {
        d[k] = opTL(d[k], x);
        lz[k] = opLL(lz[k], x);
    }
    private void push(int k) {
        if (lz[k] == eL) return;
        lzAdd(2*k, lz[k]);
        lzAdd(2*k+1, lz[k]);
        lz[k] = eL;
    }
    T sum(int a, int b, int l, int r, int k) {
        if (b <= l || r <= a) return eT;
        if (a <= l && r <= b) return d[k];
        push(k);
        int md = (l+r)/2;
        return opTT(sum(a, b, l, md, 2*k),
            sum(a, b, md, r, 2*k+1));
    }
    T single(int k) {
        k += sz;
        foreach_reverse (int i; 1..lg+1) {
            push(k>>i);
        }
        return d[k];
    }
    T sum(int a, int b) {
        assert(0 <= a && a <= b && b <= n);
        return sum(a, b, 0, sz, 1);
    }
    void add(int a, int b, L x, int l, int r, int k) {
        if (b <= l || r <= a) return;
        if (a <= l && r <= b) {
            lzAdd(k, x);
            return;
        }
        push(k);
        int md = (l+r)/2;
        add(a, b, x, l, md, 2*k);
        add(a, b, x, md, r, 2*k+1);
        d[k] = opTT(d[2*k], d[2*k+1]);
    }
    void add(int a, int b, L x) {
        assert(0 <= a && a <= b && b <= n);
        add(a, b, x, 0, sz, 1);
    }
    @property int opDollar() const {return sz;}
    struct Range {
        LazySeg* seg;
        int start, end;
        @property T sum() {
            return seg.sum(start, end);
        }
    }
    int[2] opSlice(size_t dim)(int start, int end) {
        assert(0 <= start && start <= end && end <= sz);
        return [start, end];
    }
    Range opIndex(int[2] rng) {
        return Range(&this, rng[0], rng[1]);
    }
    void opIndexOpAssign(string op : "+")(L x, int[2] rng) {
        add(rng[0], rng[1], x);
    }
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/string.d */
// module dcomp.string;

struct SA(T) {
    T[] s;

    int[] sa, rsa, lcp;
    this(in T[] s) {
        size_t n = s.length;
        this.s = s.dup;
        sa = new int[](n+1);
        rsa = new int[](n+1);
        lcp = new int[](n);
    }
}

int[] sais(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm, std.range;
    int n = _s.length.to!int;
    int[] sa = new int[](n+1);
    if (n == 0) return sa;

    auto s = _s.map!"a+1".array ~ T(0); B++;

    bool[] ls = new bool[](n+1);
    ls[n] = true;
    foreach_reverse (i; 0..n) {
        ls[i] = (s[i] == s[i+1]) ? ls[i+1] : (s[i] < s[i+1]);
    }

    int[] sumL = new int[](B+1), sumS = new int[](B+1);
    s.each!((i, c) => !ls[i] ? sumS[c]++ : sumL[c+1]++);
    foreach (i; 0..B) {
        sumL[i+1] += sumS[i];
        sumS[i+1] += sumL[i+1];
    }

    void induce(in int[] lms) {
        sa[] = -1;
        auto buf0 = sumS.dup;
        foreach (d; lms) {
            sa[buf0[s[d]]++] = d;
        }
        auto buf1 = sumL.dup;
        foreach (v; sa) {
            if (v >= 1 && !ls[v-1]) {
                sa[buf1[s[v-1]]++] = v-1;
            }
        }
        auto buf2 = sumL.dup;
        foreach_reverse (v; sa) {
            if (v >= 1 && ls[v-1]) {
                sa[--buf2[s[v-1]+1]] = v-1;
            }
        }
    }

    int[] lms = iota(1, n+1).filter!(i => !ls[i-1] && ls[i]).array;
    int[] lmsMap = new int[](n+1);
    lmsMap[] = -1; lms.each!((i, v) => lmsMap[v] = i.to!int);

    induce(lms);

    if (lms.length >= 2) {
        int m = lms.length.to!int - 1;

        auto lms2 = sa.filter!(v => lmsMap[v] != -1).array;
        int recN = 1;
        int[] recS = new int[](m);
        recS[lmsMap[lms2[1]]] = 1;
        foreach (i; 2..m+1) {
            int l = lms2[i-1], r = lms2[i];
            int nl = lms[lmsMap[l]+1], nr = lms[lmsMap[r]+1];
            if (cmp(s[l..nl+1], s[r..nr+1])) recN++;
            recS[lmsMap[lms2[i]]] = recN;
        }

        induce(lms.indexed(sais!int(recS, recN)).array);
    }

    return sa;
}

SA!T suffixArray(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm;
    int n = _s.length.to!int;
    auto saInfo = SA!T(_s);
    if (n == 0) return saInfo;

    with (saInfo) {
        sa = sais(_s, B);

        sa.each!((i, v) => rsa[v] = i.to!int);

        int h = 0;
        foreach (i; 0..n) {
            int j = sa[rsa[i]-1];
            if (h > 0) h--;
            for (; j+h < n && i+h < n; h++) {
                if (s[j+h] != s[i+h]) break;
            }
            lcp[rsa[i]-1] = h;
        }
    }
    return saInfo;
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/algorithm.d */
// module dcomp.algorithm;

import std.range.primitives;
import std.traits : isFloatingPoint, isIntegral;

T binSearch(alias pred, T)(T l, T r) if (isIntegral!T) {
    while (r-l > 1) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

T binSearch(alias pred, T)(T l, T r, int cnt = 60) if (isFloatingPoint!T) {
    foreach (i; 0..cnt) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

E minimum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? a : b)(seed, range);
}

ElementType!Range minimum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return minimum!pred(range, e);
}

E maximum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? b : a)(seed, range);
}

ElementType!Range maximum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return maximum!pred(range, e);
}

Rotator!Range rotator(Range)(Range r) {
    return Rotator!Range(r);
}

struct Rotator(Range)
if (isForwardRange!Range && hasLength!Range) {
    size_t cnt;
    Range start, now;
    this(Range r) {
        cnt = 0;
        start = r.save;
        now = r.save;
    }
    this(this) {
        start = start.save;
        now = now.save;
    }
    @property bool empty() {
        return now.empty;
    }
    @property auto front() {
        assert(!now.empty);
        import std.range : take, chain;
        return chain(now, start.take(cnt));
    }
    @property Rotator!Range save() {
        return this;
    }
    void popFront() {
        cnt++;
        now.popFront;
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/ascii.d */
// module dcomp.ascii;

struct ASCIIString {
    string s;
    alias s this;
    this(string s) {
        this.s = s;
    }
    ref immutable(char) front() const {
        return s[0];
    }
    void popFront() {
        s = s[1..$];
    }
    ref immutable(char) back() const {
        return s[$-1];
    }
    void popBack() {
        s = s[0..$-1];
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}

/+ dub.sdl:
    name "I"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner;

// import dcomp.algorithm;
// import dcomp.string;
// import dcomp.datastructure.lazyseg;

void solve() {
    string s;
    sc.read(s);
    auto saInfo = suffixArray(s);
    int n = s.length.to!int;
    auto tr = LazySeg!(long, long, (a, b)=>a+b, (a, b)=>(b==-1)?a:b, (a, b)=>(b==-1)?a:b, 0, -1)(n);
    tr[0..n] += 10^^9;
    long sm = 0;
    foreach (i; 1..n) {
        auto u = saInfo.lcp[i];
        auto le = binSearch!(x => tr[x..x+1].sum >= u)(-1, i);
        tr[le..i] += u;
        sm += tr[0..i].sum;
//        writeln(tr);
    }
    writeln(sm*2 + long(n)*(n+1)/2);
}

int main() {
    int n;
    sc.read(n);
    foreach (i; 0..n) {
        solve();
    }
    return 0;
}

Scanner sc;
static this() {
    sc = new Scanner(stdin);
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/datastructure/lazyseg.d */
// module dcomp.datastructure.lazyseg;

struct LazySeg(T, L, alias opTT, alias opTL, alias opLL, T eT, L eL) {
    const int n, sz;
    T[] d;
    L[] lz;
    @disable this();
    this(int n) {
        import std.algorithm : fill;
        import core.bitop : bsr;
        if (n == 0) return;
        int lg = n.bsr;
        if ((2^^lg) < n) lg++;
        this.n = n;
        this.sz = 2^^lg;
        d = new T[](2*this.sz); d[] = eT;
        lz = new L[](2*this.sz); lz[] = eL;
    }
    private void lzAdd(int k, L x) {
        d[k] = opTL(d[k], x);
        lz[k] = opLL(lz[k], x);
    }
    private void push(int k) {
        if (lz[k] == eL) return;
        lzAdd(2*k, lz[k]);
        lzAdd(2*k+1, lz[k]);
        lz[k] = eL;
    }
    T sum(int a, int b, int l, int r, int k) {
        if (b <= l || r <= a) return eT;
        if (a <= l && r <= b) return d[k];
        push(k);
        int md = (l+r)/2;
        return opTT(sum(a, b, l, md, 2*k),
            sum(a, b, md, r, 2*k+1));
    }
    T sum(int a, int b) {
        assert(0 <= a && a <= b && b <= n);
        return sum(a, b, 0, sz, 1);
    }
    void add(int a, int b, L x, int l, int r, int k) {
        if (b <= l || r <= a) return;
        if (a <= l && r <= b) {
            lzAdd(k, x);
            return;
        }
        push(k);
        int md = (l+r)/2;
        add(a, b, x, l, md, 2*k);
        add(a, b, x, md, r, 2*k+1);
        d[k] = opTT(d[2*k], d[2*k+1]);
    }
    void add(int a, int b, L x) {
        assert(0 <= a && a <= b && b <= n);
        add(a, b, x, 0, sz, 1);
    }
    @property int opDollar() const {return sz;}
    struct Range {
        LazySeg* seg;
        int start, end;
        @property T sum() {
            return seg.sum(start, end);
        }
    }
    int[2] opSlice(size_t dim)(int start, int end) {
        assert(0 <= start && start <= end && end <= sz);
        return [start, end];
    }
    Range opIndex(int[2] rng) {
        return Range(&this, rng[0], rng[1]);
    }
    void opIndexOpAssign(string op)(L x, int[2] rng) {
        add(rng[0], rng[1], x);
    }
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/string.d */
// module dcomp.string;

struct SA(T) {
    T[] s;

    int[] sa, rsa, lcp;
    this(in T[] s) {
        size_t n = s.length;
        this.s = s.dup;
        sa = new int[](n+1);
        rsa = new int[](n+1);
        lcp = new int[](n);
    }
}

int[] sais(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm, std.range;
    int n = _s.length.to!int;
    int[] sa = new int[](n+1);
    if (n == 0) return sa;

    auto s = _s.map!"a+1".array ~ T(0); B++;

    bool[] ls = new bool[](n+1);
    ls[n] = true;
    foreach_reverse (i; 0..n) {
        ls[i] = (s[i] == s[i+1]) ? ls[i+1] : (s[i] < s[i+1]);
    }

    int[] sumL = new int[](B+1), sumS = new int[](B+1);
    s.each!((i, c) => !ls[i] ? sumS[c]++ : sumL[c+1]++);
    foreach (i; 0..B) {
        sumL[i+1] += sumS[i];
        sumS[i+1] += sumL[i+1];
    }

    void induce(in int[] lms) {
        sa[] = -1;
        auto buf0 = sumS.dup;
        foreach (d; lms) {
            sa[buf0[s[d]]++] = d;
        }
        auto buf1 = sumL.dup;
        foreach (v; sa) {
            if (v >= 1 && !ls[v-1]) {
                sa[buf1[s[v-1]]++] = v-1;
            }
        }
        auto buf2 = sumL.dup;
        foreach_reverse (v; sa) {
            if (v >= 1 && ls[v-1]) {
                sa[--buf2[s[v-1]+1]] = v-1;
            }
        }
    }

    int[] lms = iota(1, n+1).filter!(i => !ls[i-1] && ls[i]).array;
    int[] lmsMap = new int[](n+1);
    lmsMap[] = -1; lms.each!((i, v) => lmsMap[v] = i.to!int);

    induce(lms);

    if (lms.length >= 2) {
        int m = lms.length.to!int - 1;

        auto lms2 = sa.filter!(v => lmsMap[v] != -1).array;
        int recN = 1;
        int[] recS = new int[](m);
        recS[lmsMap[lms2[1]]] = 1;
        foreach (i; 2..m+1) {
            int l = lms2[i-1], r = lms2[i];
            int nl = lms[lmsMap[l]+1], nr = lms[lmsMap[r]+1];
            if (cmp(s[l..nl+1], s[r..nr+1])) recN++;
            recS[lmsMap[lms2[i]]] = recN;
        }

        induce(lms.indexed(sais!int(recS, recN)).array);
    }

    return sa;
}

SA!T suffixArray(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm;
    int n = _s.length.to!int;
    auto saInfo = SA!T(_s);
    if (n == 0) return saInfo;

    with (saInfo) {
        sa = sais(_s, B);

        sa.each!((i, v) => rsa[v] = i.to!int);

        int h = 0;
        foreach (i; 0..n) {
            int j = sa[rsa[i]-1];
            if (h > 0) h--;
            for (; j+h < n && i+h < n; h++) {
                if (s[j+h] != s[i+h]) break;
            }
            lcp[rsa[i]-1] = h;
        }
    }
    return saInfo;
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/ascii.d */
// module dcomp.ascii;

struct ASCIIString {
    string s;
    alias s this;
    this(string s) {
        this.s = s;
    }
    ref immutable(char) front() const {
        return s[0];
    }
    void popFront() {
        s = s[1..$];
    }
    ref immutable(char) back() const {
        return s[$-1];
    }
    void popBack() {
        s = s[0..$-1];
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/algorithm.d */
// module dcomp.algorithm;

import std.range.primitives;
import std.traits : isFloatingPoint, isIntegral;

T binSearch(alias pred, T)(T l, T r) if (isIntegral!T) {
    while (r-l > 1) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

T binSearch(alias pred, T)(T l, T r, int cnt = 60) if (isFloatingPoint!T) {
    foreach (i; 0..cnt) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

E minimum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? a : b)(seed, range);
}

ElementType!Range minimum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return minimum!pred(range, e);
}

E maximum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? b : a)(seed, range);
}

ElementType!Range maximum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return maximum!pred(range, e);
}

Rotator!Range rotator(Range)(Range r) {
    return Rotator!Range(r);
}

struct Rotator(Range)
if (isForwardRange!Range && hasLength!Range) {
    size_t cnt;
    Range start, now;
    this(Range r) {
        cnt = 0;
        start = r.save;
        now = r.save;
    }
    this(this) {
        start = start.save;
        now = now.save;
    }
    @property bool empty() {
        return now.empty;
    }
    @property auto front() {
        assert(!now.empty);
        import std.range : take, chain;
        return chain(now, start.take(cnt));
    }
    @property Rotator!Range save() {
        return this;
    }
    void popFront() {
        cnt++;
        now.popFront;
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}

/+ dub.sdl:
    name "I"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv;
// import dcomp.foundation, dcomp.scanner;

// import dcomp.algorithm;
// import dcomp.string;
// import dcomp.datastructure.lazyseg;

void solve() {
    string s;
    sc.read(s);
    auto saInfo = suffixArray(s);
    int n = s.length.to!int;
    auto tr = LazySeg!(int, int, (a, b)=>a+b, (a, b)=>(b==-1)?a:b, (a, b)=>(b==-1)?a:b, 0, -1)(n);
    tr[0..n] += 10^^9;
    long sm = 0;
    foreach (i; 1..n) {
        auto u = saInfo.lcp[i];
        auto le = binSearch!(x => tr[x..x+1].sum >= u)(-1, i);
        tr[le..i] += u;
        sm += tr[0..i].sum;
//        writeln(tr);
    }
    writeln(sm*2 + long(n)*(n+1)/2);
}

int main() {
    int n;
    sc.read(n);
    foreach (i; 0..n) {
        solve();
    }
    return 0;
}

Scanner sc;
static this() {
    sc = new Scanner(stdin);
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/datastructure/lazyseg.d */
// module dcomp.datastructure.lazyseg;

struct LazySeg(T, L, alias opTT, alias opTL, alias opLL, T eT, L eL) {
    const int n, sz;
    T[] d;
    L[] lz;
    @disable this();
    this(int n) {
        import std.algorithm : fill;
        import core.bitop : bsr;
        if (n == 0) return;
        int lg = n.bsr;
        if ((2^^lg) < n) lg++;
        this.n = n;
        this.sz = 2^^lg;
        d = new T[](2*this.sz); d[] = eT;
        lz = new L[](2*this.sz); lz[] = eL;
    }
    private void lzAdd(int k, L x) {
        d[k] = opTL(d[k], x);
        lz[k] = opLL(lz[k], x);
    }
    private void push(int k) {
        if (lz[k] == eL) return;
        lzAdd(2*k, lz[k]);
        lzAdd(2*k+1, lz[k]);
        lz[k] = eL;
    }
    T sum(int a, int b, int l, int r, int k) {
        if (b <= l || r <= a) return eT;
        if (a <= l && r <= b) return d[k];
        push(k);
        int md = (l+r)/2;
        return opTT(sum(a, b, l, md, 2*k),
            sum(a, b, md, r, 2*k+1));
    }
    T sum(int a, int b) {
        assert(0 <= a && a <= b && b <= n);
        return sum(a, b, 0, sz, 1);
    }
    void add(int a, int b, L x, int l, int r, int k) {
        if (b <= l || r <= a) return;
        if (a <= l && r <= b) {
            lzAdd(k, x);
            return;
        }
        push(k);
        int md = (l+r)/2;
        add(a, b, x, l, md, 2*k);
        add(a, b, x, md, r, 2*k+1);
        d[k] = opTT(d[2*k], d[2*k+1]);
    }
    void add(int a, int b, L x) {
        assert(0 <= a && a <= b && b <= n);
        add(a, b, x, 0, sz, 1);
    }
    @property int opDollar() const {return sz;}
    struct Range {
        LazySeg* seg;
        int start, end;
        @property T sum() {
            return seg.sum(start, end);
        }
    }
    int[2] opSlice(size_t dim)(int start, int end) {
        assert(0 <= start && start <= end && end <= sz);
        return [start, end];
    }
    Range opIndex(int[2] rng) {
        return Range(&this, rng[0], rng[1]);
    }
    void opIndexOpAssign(string op)(L x, int[2] rng) {
        add(rng[0], rng[1], x);
    }
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/string.d */
// module dcomp.string;

struct SA(T) {
    T[] s;

    int[] sa, rsa, lcp;
    this(in T[] s) {
        size_t n = s.length;
        this.s = s.dup;
        sa = new int[](n+1);
        rsa = new int[](n+1);
        lcp = new int[](n);
    }
}

int[] sais(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm, std.range;
    int n = _s.length.to!int;
    int[] sa = new int[](n+1);
    if (n == 0) return sa;

    auto s = _s.map!"a+1".array ~ T(0); B++;

    bool[] ls = new bool[](n+1);
    ls[n] = true;
    foreach_reverse (i; 0..n) {
        ls[i] = (s[i] == s[i+1]) ? ls[i+1] : (s[i] < s[i+1]);
    }

    int[] sumL = new int[](B+1), sumS = new int[](B+1);
    s.each!((i, c) => !ls[i] ? sumS[c]++ : sumL[c+1]++);
    foreach (i; 0..B) {
        sumL[i+1] += sumS[i];
        sumS[i+1] += sumL[i+1];
    }

    void induce(in int[] lms) {
        sa[] = -1;
        auto buf0 = sumS.dup;
        foreach (d; lms) {
            sa[buf0[s[d]]++] = d;
        }
        auto buf1 = sumL.dup;
        foreach (v; sa) {
            if (v >= 1 && !ls[v-1]) {
                sa[buf1[s[v-1]]++] = v-1;
            }
        }
        auto buf2 = sumL.dup;
        foreach_reverse (v; sa) {
            if (v >= 1 && ls[v-1]) {
                sa[--buf2[s[v-1]+1]] = v-1;
            }
        }
    }

    int[] lms = iota(1, n+1).filter!(i => !ls[i-1] && ls[i]).array;
    int[] lmsMap = new int[](n+1);
    lmsMap[] = -1; lms.each!((i, v) => lmsMap[v] = i.to!int);

    induce(lms);

    if (lms.length >= 2) {
        int m = lms.length.to!int - 1;

        auto lms2 = sa.filter!(v => lmsMap[v] != -1).array;
        int recN = 1;
        int[] recS = new int[](m);
        recS[lmsMap[lms2[1]]] = 1;
        foreach (i; 2..m+1) {
            int l = lms2[i-1], r = lms2[i];
            int nl = lms[lmsMap[l]+1], nr = lms[lmsMap[r]+1];
            if (cmp(s[l..nl+1], s[r..nr+1])) recN++;
            recS[lmsMap[lms2[i]]] = recN;
        }

        induce(lms.indexed(sais!int(recS, recN)).array);
    }

    return sa;
}

SA!T suffixArray(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm;
    int n = _s.length.to!int;
    auto saInfo = SA!T(_s);
    if (n == 0) return saInfo;

    with (saInfo) {
        sa = sais(_s, B);

        sa.each!((i, v) => rsa[v] = i.to!int);

        int h = 0;
        foreach (i; 0..n) {
            int j = sa[rsa[i]-1];
            if (h > 0) h--;
            for (; j+h < n && i+h < n; h++) {
                if (s[j+h] != s[i+h]) break;
            }
            lcp[rsa[i]-1] = h;
        }
    }
    return saInfo;
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/ascii.d */
// module dcomp.ascii;

struct ASCIIString {
    string s;
    alias s this;
    this(string s) {
        this.s = s;
    }
    ref immutable(char) front() const {
        return s[0];
    }
    void popFront() {
        s = s[1..$];
    }
    ref immutable(char) back() const {
        return s[$-1];
    }
    void popBack() {
        s = s[0..$-1];
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/algorithm.d */
// module dcomp.algorithm;

import std.range.primitives;
import std.traits : isFloatingPoint, isIntegral;

T binSearch(alias pred, T)(T l, T r) if (isIntegral!T) {
    while (r-l > 1) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

T binSearch(alias pred, T)(T l, T r, int cnt = 60) if (isFloatingPoint!T) {
    foreach (i; 0..cnt) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

E minimum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? a : b)(seed, range);
}

ElementType!Range minimum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return minimum!pred(range, e);
}

E maximum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? b : a)(seed, range);
}

ElementType!Range maximum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return maximum!pred(range, e);
}

Rotator!Range rotator(Range)(Range r) {
    return Rotator!Range(r);
}

struct Rotator(Range)
if (isForwardRange!Range && hasLength!Range) {
    size_t cnt;
    Range start, now;
    this(Range r) {
        cnt = 0;
        start = r.save;
        now = r.save;
    }
    this(this) {
        start = start.save;
        now = now.save;
    }
    @property bool empty() {
        return now.empty;
    }
    @property auto front() {
        assert(!now.empty);
        import std.range : take, chain;
        return chain(now, start.take(cnt));
    }
    @property Rotator!Range save() {
        return this;
    }
    void popFront() {
        cnt++;
        now.popFront;
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}

/+ dub.sdl:
    name "I"
    dependency "dcomp" version=">=0.6.0"
+/

import std.stdio, std.algorithm, std.range, std.conv, std.traits;
// import dcomp.foundation, dcomp.scanner;
// import dcomp.array;
// import dcomp.algorithm;
// import dcomp.string;

/// 遅延伝搬Segment Tree
struct LazySeg(T, L, alias opTT, alias opTL, alias opLL, T eT, L eL) {
    const int n, sz, lg;
    T[] d;
    L[] lz;
    @disable this();
    this(int n) {
        import std.algorithm : fill, each;
        import core.bitop : bsr;
        if (n == 0) return;
        int lg = n.bsr;
        if ((2^^lg) < n) lg++;
        this.n = n;
        this.sz = 2^^lg;
        this.lg = lg;
        d = new T[](2*this.sz);
        d.each!((ref x) => x = eT);
        lz = new L[](2*this.sz);
        lz.each!((ref x) => x = eL);
    }
    private void lzAdd(int k, L x) {
        d[k] = opTL(d[k], x);
        lz[k] = opLL(lz[k], x);
    }
    private void push(int k) {
        if (lz[k] == eL) return;
        lzAdd(2*k, lz[k]);
        lzAdd(2*k+1, lz[k]);
        lz[k] = eL;
    }
    //d[a]+d[a+1]+...+d[b-1]
    T sum(int a, int b, int l, int r, int k) {
        if (b <= l || r <= a) return eT;
        if (a <= l && r <= b) return d[k];
        push(k);
        int md = (l+r)/2;
        return opTT(sum(a, b, l, md, 2*k),
            sum(a, b, md, r, 2*k+1));
    }
    T single(int k) {
        k += sz;
        foreach_reverse (int i; 1..lg+1) {
            push(k>>i);
        }
        return d[k];
    }
    void singleSet(T x, int k) {
        k += sz;
        foreach_reverse (int i; 1..lg+1) {
            push(k>>i);
        }
        d[k] = x;
        foreach (int i; 1..lg+1) {
            d[k>>i] = opTT(d[2*(k>>i)], d[2*(k>>i)+1]);
        }
    }
    T sum(int a, int b) {
        assert(0 <= a && a <= b && b <= n);
        return sum(a, b, 0, sz, 1);
    }
    void add(int a, int b, L x, int l, int r, int k) {
        if (b <= l || r <= a) return;
        if (a <= l && r <= b) {
            lzAdd(k, x);
            return;
        }
        push(k);
        int md = (l+r)/2;
        add(a, b, x, l, md, 2*k);
        add(a, b, x, md, r, 2*k+1);
        d[k] = opTT(d[2*k], d[2*k+1]);
    }
    void add(int a, int b, L x) {
        assert(0 <= a && a <= b && b <= n);
        add(a, b, x, 0, sz, 1);
    }
    @property int opDollar() const {return sz;}
    struct Range {
        LazySeg* seg;
        int start, end;
        @property T sum() {
            return seg.sum(start, end);
        }
    }
    T opIndex(int k) {
        assert(0 <= k && k < n);
        return single(k);
    }
    void opIndexAssign(T x, int k) {
        assert(0 <= k && k < n);
        singleSet(x, k);
    }
    int[2] opSlice(size_t dim)(int start, int end) {
        assert(0 <= start && start <= end && end <= sz);
        return [start, end];
    }
    Range opIndex(int[2] rng) {
        return Range(&this, rng[0], rng[1]);
    }
    void opIndexOpAssign(string op : "+")(L x, int[2] rng) {
        add(rng[0], rng[1], x);
    }
}

int binSearchLeft(alias pred, TR)(TR t, int a, int b)
if (isInstanceOf!(LazySeg, TR)) {
    alias args = TemplateArgsOf!TR;
    alias opTT = args[2];
    with (t) {
        auto x = args[5];
        if (pred(x)) return a-1;
        int pos = a;
        void f(int a, int b, int l, int r, int k) {
            if (b <= l || r <= a) return;
            if (a <= l && r <= b && !pred(opTT(x, d[k]))) {
                x = opTT(x, d[k]);
                pos = r;
                return;
            }
            if (l+1 == r) return;
            push(k);
            int md = (l+r)/2;
            f(a, b, l, md, 2*k);
            if (pos >= md) f(a, b, md, r, 2*k+1);
        }
        f(a, b, 0, sz, 1);
        return pos;
    }
}

void solve() {
    string s;
    sc.read(s);
    auto saInfo = suffixArray(s);
    int n = s.length.to!int;
    import std.typecons;
    alias T = Tuple!(long, int, int);
    auto tr = LazySeg!(T, int,
        (a, b)=>T(a[0]+b[0], a[1]+b[1], max(a[2], b[2])),
        (a, b)=>T(b * a[1], a[1], b),
        (a, b)=>b,
        T(0L, 1, -(10^^9)), -1)(n);
    tr[0..n] += 10^^9;
    long sm = 0;
    foreach (i; 1..n) {
        auto u = saInfo.lcp[i];
        auto le = tr.binSearchLeft!(x => x[2] >= u)(0, i);
        tr[le..i] += u;
        sm += tr[0..i].sum[0];
//        writeln(tr);
    }
    writeln(sm*2 + long(n)*(n+1)/2);
}

int main() {
    int n;
    sc.read(n);
    foreach (i; 0..n) {
        solve();
    }
    return 0;
}

Scanner sc;
static this() {
    sc = new Scanner(stdin);
}
/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/array.d */
// module dcomp.array;

T[N] fixed(T, size_t N)(T[N] a) {return a;}

struct FastAppender(A) {
    import std.algorithm : max;
    import std.range.primitives : ElementEncodingType;
    import core.stdc.string : memcpy;

    private alias T = ElementEncodingType!A;
    private T* _data;
    private size_t len, cap;

    @property size_t length() {return len;}

    void reserve(size_t nlen) {
        import core.memory : GC;
        if (nlen <= cap) return;

        void* nx = GC.malloc(nlen * T.sizeof);

        cap = nlen;
        if (len) memcpy(nx, _data, len * T.sizeof);
        _data = cast(T*)(nx);
    }

    void opOpAssign(string op : "~")(T item) {
        if (len == cap) {
            reserve(max(4, cap*2));
        }
        _data[len++] = item;
    }

    void clear() {
        len = 0;
    }

    T[] data() {
        return (_data) ? _data[0..len] : null;
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/string.d */
// module dcomp.string;

struct SA(T) {
    T[] s;

    int[] sa, rsa, lcp;
    this(in T[] s) {
        size_t n = s.length;
        this.s = s.dup;
        sa = new int[](n+1);
        rsa = new int[](n+1);
        lcp = new int[](n);
    }
}

int[] sais(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm, std.range;
    int n = _s.length.to!int;
    int[] sa = new int[](n+1);
    if (n == 0) return sa;

    auto s = _s.map!"a+1".array ~ T(0); B++;

    bool[] ls = new bool[](n+1);
    ls[n] = true;
    foreach_reverse (i; 0..n) {
        ls[i] = (s[i] == s[i+1]) ? ls[i+1] : (s[i] < s[i+1]);
    }

    int[] sumL = new int[](B+1), sumS = new int[](B+1);
    s.each!((i, c) => !ls[i] ? sumS[c]++ : sumL[c+1]++);
    foreach (i; 0..B) {
        sumL[i+1] += sumS[i];
        sumS[i+1] += sumL[i+1];
    }

    void induce(in int[] lms) {
        sa[] = -1;
        auto buf0 = sumS.dup;
        foreach (d; lms) {
            sa[buf0[s[d]]++] = d;
        }
        auto buf1 = sumL.dup;
        foreach (v; sa) {
            if (v >= 1 && !ls[v-1]) {
                sa[buf1[s[v-1]]++] = v-1;
            }
        }
        auto buf2 = sumL.dup;
        foreach_reverse (v; sa) {
            if (v >= 1 && ls[v-1]) {
                sa[--buf2[s[v-1]+1]] = v-1;
            }
        }
    }

    int[] lms = iota(1, n+1).filter!(i => !ls[i-1] && ls[i]).array;
    int[] lmsMap = new int[](n+1);
    lmsMap[] = -1; lms.each!((i, v) => lmsMap[v] = i.to!int);

    induce(lms);

    if (lms.length >= 2) {
        int m = lms.length.to!int - 1;

        auto lms2 = sa.filter!(v => lmsMap[v] != -1).array;
        int recN = 1;
        int[] recS = new int[](m);
        recS[lmsMap[lms2[1]]] = 1;
        foreach (i; 2..m+1) {
            int l = lms2[i-1], r = lms2[i];
            int nl = lms[lmsMap[l]+1], nr = lms[lmsMap[r]+1];
            if (cmp(s[l..nl+1], s[r..nr+1])) recN++;
            recS[lmsMap[lms2[i]]] = recN;
        }

        induce(lms.indexed(sais!int(recS, recN)).array);
    }

    return sa;
}

SA!T suffixArray(T)(in T[] _s, int B = 200) {
    import std.conv, std.algorithm;
    int n = _s.length.to!int;
    auto saInfo = SA!T(_s);
    if (n == 0) return saInfo;

    with (saInfo) {
        sa = sais(_s, B);

        sa.each!((i, v) => rsa[v] = i.to!int);

        int h = 0;
        foreach (i; 0..n) {
            int j = sa[rsa[i]-1];
            if (h > 0) h--;
            for (; j+h < n && i+h < n; h++) {
                if (s[j+h] != s[i+h]) break;
            }
            lcp[rsa[i]-1] = h;
        }
    }
    return saInfo;
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/scanner.d */
// module dcomp.scanner;

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/algorithm.d */
// module dcomp.algorithm;

import std.range.primitives;
import std.traits : isFloatingPoint, isIntegral;

T binSearch(alias pred, T)(T l, T r) if (isIntegral!T) {
    while (r-l > 1) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

T binSearch(alias pred, T)(T l, T r, int cnt = 60) if (isFloatingPoint!T) {
    foreach (i; 0..cnt) {
        T md = (l+r)/2;
        if (!pred(md)) l = md;
        else r = md;
    }
    return r;
}

E minimum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? a : b)(seed, range);
}

ElementType!Range minimum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return minimum!pred(range, e);
}

E maximum(alias pred = "a < b", Range, E = ElementType!Range)(Range range, E seed)
if (isInputRange!Range && !isInfinite!Range) {
    import std.algorithm, std.functional;
    return reduce!((a, b) => binaryFun!pred(a, b) ? b : a)(seed, range);
}

ElementType!Range maximum(alias pred = "a < b", Range)(Range range) {
    assert(!range.empty, "range must not empty");
    auto e = range.front; range.popFront;
    return maximum!pred(range, e);
}

Rotator!Range rotator(Range)(Range r) {
    return Rotator!Range(r);
}

struct Rotator(Range)
if (isForwardRange!Range && hasLength!Range) {
    size_t cnt;
    Range start, now;
    this(Range r) {
        cnt = 0;
        start = r.save;
        now = r.save;
    }
    this(this) {
        start = start.save;
        now = now.save;
    }
    @property bool empty() {
        return now.empty;
    }
    @property auto front() {
        assert(!now.empty);
        import std.range : take, chain;
        return chain(now, start.take(cnt));
    }
    @property Rotator!Range save() {
        return this;
    }
    void popFront() {
        cnt++;
        now.popFront;
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/ascii.d */
// module dcomp.ascii;

struct ASCIIString {
    string s;
    alias s this;
    this(string s) {
        this.s = s;
    }
    ref immutable(char) front() const {
        return s[0];
    }
    void popFront() {
        s = s[1..$];
    }
    ref immutable(char) back() const {
        return s[$-1];
    }
    void popBack() {
        s = s[0..$-1];
    }
}

/* IMPORT /Users/yosupo/Program/dcomp/source/dcomp/foundation.d */
// module dcomp.foundation;

static if (__VERSION__ <= 2070) {
    template fold(fun...) if (fun.length >= 1) {
        auto fold(R, S...)(R r, S seed) {
            import std.algorithm : reduce;
            static if (S.length < 2) {
                return reduce!fun(seed, r);
            } else {
                import std.typecons : tuple;
                return reduce!fun(tuple(seed), r);
            }
        }
    }

}
version (X86) static if (__VERSION__ < 2071) {
    import core.bitop : bsf, bsr, popcnt;
    int bsf(ulong v) {
        foreach (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int bsr(ulong v) {
        foreach_reverse (i; 0..64) {
            if (v & (1UL << i)) return i;
        }
        return -1;
    }
    int popcnt(ulong v) {
        int c = 0;
        foreach (i; 0..64) {
            if (v & (1UL << i)) c++;
        }
        return c;
    }
}


// Cheese-Cracker: cheese-cracker.github.io

void theCode(){
    int n;
    n = scan!int;
    ll[] res, arr;
    auto w = scan!(dchar[]);
    w.each!(a => arr ~= to!long(a - '0'));
    ll cs = 0, ps = -1;
    for(int i = 0; i < n; ++i){
        res ~= 2 - arr[i];
        if(res[i] == 2) --res[i];
        cs = res[i]+arr[i];
        if(cs == ps){
            res[i] = !res[i];
        }
        cs = res[i]+arr[i];
        write(res[i]);
        ps = cs;
    }
    writeln;
}

void main(){
    long tests = 1;
    tests = scan;        // Toggle!
    while(tests--) theCode();
}

/*********  That's All Folks!  *********/
import std.stdio, std.random, std.functional, std.container, std.algorithm;
import std.numeric, std.range, std.typecons, std.string, std.math, std.conv;
string[] tk; T scan(T=long)(){while(!tk.length)tk = readln.split; string a=tk.front; tk.popFront; return a.to!T;}
T[] scanArray(T=long)(){ auto r = readln.split.to!(T[]); return r; }
void show(A...)(A a){ debug{ foreach(t; a){stderr.write(t, "| ");} stderr.writeln; } }
alias ll = long, tup = Tuple!(long, "x",  long, "y");

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric, std.container, std.range;

void get(Args...)(ref Args args)
{
    import std.traits, std.meta, std.typecons;

    static if (Args.length == 1) {
        alias Arg = Args[0];

        static if (isArray!Arg) {
          static if (isSomeChar!(ElementType!Arg)) {
            args[0] = readln.chomp.to!Arg;
          } else {
            args[0] = readln.split.to!Arg;
          }
        } else static if (isTuple!Arg) {
            auto input = readln.split;
            static foreach (i; 0..Fields!Arg.length) {
                args[0][i] = input[i].to!(Fields!Arg[i]);
            }
        } else {
            args[0] = readln.chomp.to!Arg;
        }
    } else {
        auto input = readln.split;
        assert(input.length == Args.length);

        static foreach (i; 0..Args.length) {
            args[i] = input[i].to!(Args[i]);
        }
    }
}

void get_lines(Args...)(size_t N, ref Args args)
{
    import std.traits, std.range;

    static foreach (i; 0..Args.length) {
        static assert(isArray!(Args[i]));
        args[i].length = N;
    }

    foreach (i; 0..N) {
        static if (Args.length == 1) {
            get(args[0][i]);
        } else {
            auto input = readln.split;
            static foreach (j; 0..Args.length) {
                args[j][i] = input[j].to!(ElementType!(Args[j]));
            }
        }
    }
}

void main()
{
    int T; get(T);
    while (T--) {
        int N; get(N);
        char[] b; get(b);
        char[] a;
        char last;
        foreach (i, c; b) {
            switch (c) {
                case '0':
                    if (last == '1') {
                        a ~= '0';
                        last = '0';
                    } else {
                        a ~= '1';
                        last = '1';
                    }
                    break;
                case '1':
                    if (last == '2') {
                        a ~= '0';
                        last = '1';
                    } else {
                        a ~= '1';
                        last = '2';
                    }
                    break;
                default:
            }
        }
        writeln(a);
    }
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto s = readln.strip.map !(q{a - '0'}).array;
		int [] t;
		int prev = -1;
		foreach (ref c; s)
		{
			auto cur = (c + 1 != prev);
			t ~= cur;
			prev = c + cur;
		}
		writefln !("%(%s%)") (t);
	}
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(ref long x, long y) { x = (x + y) % mod; }
void mods(ref long x, long y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(ref long x, long y) { x = (x * y) % mod; }
void modpow(ref long x, long y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(ref long x, long y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new string[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto b = RD!string;

		ans[ti] ~= '1';
		long x;
		if (b[0] == '1')
			x = 2;
		else
			x = 1;

		foreach (i; 1..n)
		{
			if (x == 2)
			{
				x = 1;
				if (b[i] == '0')
					ans[ti] ~= '1';
				else
					ans[ti] ~= '0';
			}
			else if (x == 1)
			{
				if (b[i] == '0')
				{
					ans[ti] ~= '0';
					x = 0;
				}
				else
				{
					ans[ti] ~= '1';
					x = 2;
				}
			}
			else
			{
				ans[ti] ~= '1';
				if (b[i] == '0')
					x = 1;
				else
					x = 2;
			}
		}
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}


import std.stdio;
import std.string : split, strip;
import std.algorithm : map, fold;
import std.conv : to;
import std.range : enumerate;
import std.typecons : tuple;

void main()
{
  int t;
  readf!"%d\n"(t);

  foreach (i; 0..t) {
    int n;
    readf!"%d\n"(n);
    auto a = readln.strip.split.map!(to!int);
    auto d = a.enumerate.fold!((a, b) {
      if (b.index % 2 != b.value % 2) {
        a[b.index % 2]++;
      }
      return a;
    })([0, 0]);

    if (d[0] == d[1]) {
      writeln(d[0]);
    } else {
      writeln(-1);
    }
  }
}

import std.stdio, std.conv, std.functional, std.string;
import std.algorithm, std.array, std.container, std.range, std.typecons;
import std.bigint, std.numeric, std.math, std.random;
import core.bitop;

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998_244_353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { y.modpow(mod - 2); x.modm(y); }

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto n = RD!int;
		auto a = RDA!int;
		int cnt0, cnt1;
		foreach (i; 0..n)
		{
			if (i % 2 != a[i] % 2)
			{
				if (i % 2)
					++cnt1;
				else
					++cnt0;
			}
		}
		if (cnt0 != cnt1)
		{
			ans[ti] = -1;
		}
		else
		{
			ans[ti] = cnt0;
		}
	}

	foreach (e; ans)
	{
		writeln(e);
	}
	stdout.flush;
	debug readln;
}


immutable multi = false;

void solve(int tc)
{
	auto n = readInt!int;
	auto c = ma(n, readInt!long);
	foreach(i, ref ci; c)
	{
		if (i % 2 == 0)
		{
			ci = ci;
		}
		else
		{
			ci = -ci;
		}
	}
	auto psum = new long[](n + 1);
	psum[0] = 0;
	foreach(i, ci; c)
	{
		psum[i+1] = psum[i] + ci;
	}
	auto psumMin = Sparse!(long, min, "min")(psum);
	long ways = 0;
	void countFor(int i, int j)
	{
		assert(i < j);
		assert(i % 2 == 0 && j % 2 == 1);
		if (j == i + 1)
		{
			assert(c[i] > 0 && -c[j] > 0);
			ways += min(c[i], -c[j]);
			return;
		}
		auto pi = psum[i+1];
		auto mr = psumMin[i+2..j+1].min - pi;
		auto rqOpen = max(0, -mr);
		if (rqOpen > c[i]) return;
		auto rqClose = psum[j] - psum[i+1] + rqOpen;
		assert(rqClose >= 0);
		// open >= rqOpen
		// open <= c[i]
		// open + psum[j] - psum[i+1] <= -c[j]
		// rqOpen <= open <= min(c[i], -c[j] - psum[j] + psum[i+1])
		auto low = rqOpen;
		auto high = min(c[i], -c[j]-psum[j]+psum[i+1]);
		if (low > high) return;
		ways += high - low + 1;
	}
	foreach(i; 0 .. n)
	{
		foreach(j; i + 1 .. n)
		{
			if (i % 2 == 0 && j % 2 == 1)
				countFor(i, j);
		}
	}
	ways.writeln;
}

//{{{
void main()
{
	auto t = multi? readInt!int : 1;
	foreach(tc; 0 .. t) solve(tc);
}
//}}}
// input {{{
int currChar;
static this()
{
	currChar = ' ';
}

char topChar()
{
	return cast(char) currChar;
}

void popChar()
{
	import core.stdc.stdio;
	currChar = getchar();
}

auto readInt(T)()
{
	T num = 0;
	int sgn = 0;
	while (topChar.isWhite)
		popChar;
	while (topChar == '-' || topChar == '+')
	{
		sgn ^= (topChar == '-');
		popChar;
	}
	while (topChar.isDigit)
	{
		num *= 10;
		num += (topChar - '0');
		popChar;
	}
	if (sgn)
		return -num;
	return num;
}

string readString()
{
	string res = "";
	while (topChar.isWhite)
		popChar;
	while (!topChar.isWhite)
	{
		res ~= topChar;
		popChar;
	}
	return res;
}
void writes(T...)(T t)
{
	static foreach(i, ti; t)
	{
		static if (isIterable!(T[i]))
		{
			foreach(e; ti)
			{
				write(e, " ");
			}
		}
	}
}
auto ra(V)()
{
	int n = readInt!int;
	return ma(n, readInt!V);
}
auto rt(V)()
{
	int n = readInt!int;
	int m = readInt!int;
	return ma(n, ma(m, readInt!V));
}
auto rbg()
{
	int n = readInt!int;
	int m = readInt!int;
	auto adj = new int[][](n);
	foreach(i; 0 .. m)
	{
		auto u = readInt!int - 1;
		auto v = readInt!int - 1;
		adj[u] ~= v;
		adj[v] ~= u;
	}
	return adj;
}
auto ma(V)(size_t n, lazy V v)
{
	auto arr = new V[](n);
	foreach(ref ai; arr) ai = v;
	return arr;
}
// }}}
// imports {{{
import std.stdio;
import std.algorithm;
import std.typecons;
import std.math;
import std.numeric;
import std.container;
import std.range;
import std.array;
import std.ascii;
// }}}

// sparse table V, f, fName {{{
struct Sparse(V, alias f, string fName = "value")
{
	import std.math : log2;
	V[][] _table;
	int[] maxPow;
	this(V[] values)
	{
		auto n = values.length;
		maxPow = new int[](n + 1);
		maxPow[0] = int.min;
		maxPow[1] = 0;
		foreach(i; 2 .. n + 1)
		{
			int prev = maxPow[i - 1];
			maxPow[i] = prev;
			prev = (1 << prev);
			if (prev * 2 <= i) maxPow[i]++;
		}
		_table = new V[][](maxPow[n] + 1, n);
		_table[0][] = values[];

		foreach(p; 1 .. maxPow[n] + 1)
		foreach(i; 0 .. n - (1<<p) + 1)
			_table[p][i] = f(_table[p-1][i], _table[p-1][i+(1<<(p-1))]);
	}
	int[2] opSlice(size_t i)(size_t start, size_t end) if (i == 0)
	{
		return [cast(int)start, cast(int)end];
	}
	auto opIndex(int[2] slice)
	{
		int sliceLen = slice[1] - slice[0];
		auto x = maxPow[sliceLen];
		auto twoX = (1 << x);
		auto p1 = _table[x][slice[0]];
		auto p2 = _table[x][slice[1] - twoX];
		struct Ans
		{
			mixin(q{V }, fName, q{;});
		}
		return Ans(f(p1, p2));
	}
}

unittest
{
	import std.algorithm;
	import std.stdio;
	alias MinQ = Sparse!(int, min, "min");
	writeln("testing");
	int[] array = [1, 2, 3, 4, -2, -2, -3, 0, 10];
	auto minQ = MinQ(array);
	foreach(i; 0 .. array.length)
	{
		foreach(j; i + 1 .. array.length + 1)
		{
			assert(minQ[i .. j].min == array[i .. j].fold!min);
		}
	}
}
// }}}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto c = readln.splitter.map !(to !(long)).array;

		int [long] pos;
		long balance = 0;
		pos[balance] = 0;
		foreach (int i, num; c)
		{
			balance += num * ((i & 1) ? -1 : +1);
			pos[balance] = int.max;
		}
		auto posToSort = pos.byKey.array;
		sort (posToSort);
		foreach (int k, long v; posToSort)
		{
			pos[v] = k;
		}
		debug {writeln (posToSort);}

		auto value = new long [pos.length];
		long res = 0;
		balance = 0;
		foreach (int i, num; c)
		{
			auto oldBalance = balance;
			balance += num * ((i & 1) ? -1 : +1);
			auto oldPos = pos[oldBalance];
			auto newPos = pos[balance];
			while (oldPos < newPos)
			{
				value[oldPos] += 1;
				oldPos += 1;
			}
			while (oldPos > newPos)
			{
				auto len = (posToSort[oldPos] -
				   posToSort[oldPos - 1]);
				value[oldPos] = 0;
				oldPos -= 1;
				res += value[oldPos] +
				    ((value[oldPos] > 0) ? (len - 1) : 0);
			}
			debug {writeln (value, " ", res, " ", balance);}
		}

		writeln (res);
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto c = readln.splitter.map !(to !(long)).array;

		int [long] pos;
		long balance = 0;
		pos[balance] = 0;
		foreach (int i, num; c)
		{
			balance += num * ((i & 1) ? -1 : +1);
			pos[balance] = int.max;
		}
		auto posToSort = pos.byKey.array;
		sort (posToSort);
		foreach (int k, long v; posToSort)
		{
			pos[v] = k;
		}
		debug {writeln (posToSort);}

		auto value = new long [pos.length];
		long res = 0;
		balance = 0;
		foreach (int i, num; c)
		{
			auto oldBalance = balance;
			balance += num * ((i & 1) ? -1 : +1);
			auto oldPos = pos[oldBalance];
			auto newPos = pos[balance];
			while (oldPos < newPos)
			{
				value[oldPos] += 1;
				oldPos += 1;
			}
			while (oldPos > newPos)
			{
				auto len = (posToSort[oldPos] -
				   posToSort[oldPos - 1]);
				value[oldPos] = 0;
				oldPos -= 1;
				res += value[oldPos] +
				    (value[oldPos > 0] ? (len - 1) : 0);
			}
			debug {writeln (value, " ", res, " ", balance);}
		}

		writeln (res);
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto c = readln.splitter.map !(to !(long)).array;

		int [long] pos;
		long balance = 0;
		pos[balance] = 0;
		foreach (int i, num; c)
		{
			balance += num * ((i & 1) ? -1 : +1);
			pos[balance] = int.max;
		}
		auto posToSort = pos.byKey.array;
		sort (posToSort);
		foreach (int k, long v; posToSort)
		{
			pos[v] = k;
		}
		debug {writeln (posToSort);}

		auto value = new long [pos.length];
		long res = 0;
		balance = 0;
		foreach (int i, num; c)
		{
			auto oldBalance = balance;
			balance += num * ((i & 1) ? -1 : +1);
			auto oldPos = pos[oldBalance];
			auto newPos = pos[balance];
			while (oldPos < newPos)
			{
				value[oldPos] += 1;
				oldPos += 1;
			}
			while (oldPos > newPos)
			{
				auto len = (posToSort[oldPos] -
				   posToSort[oldPos - 1]);
				value[oldPos] = 0;
				oldPos -= 1;
				res += value[oldPos] + len - 1;
			}
			debug {writeln (value, " ", res, " ", balance);}
		}

		writeln (res);
	}
}

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf !(" %s") (n) > 0)
	{
		readln;
		auto c = readln.splitter.map !(to !(long)).array;

		int [long] pos;
		long balance = 0;
		pos[balance] = 0;
		foreach (int i, num; c)
		{
			balance += num * ((i & 1) ? -1 : +1);
			pos[balance] = int.max;
		}
		auto posToSort = pos.byKey.array;
		sort (posToSort);
		foreach (int k, long v; posToSort)
		{
			pos[v] = k;
		}
		debug {writeln (posToSort);}

		auto value = new long [pos.length];
		long res = 0;
		balance = 0;
		foreach (int i, num; c)
		{
			auto oldBalance = balance;
			balance += num * ((i & 1) ? -1 : +1);
			auto oldPos = pos[oldBalance];
			auto newPos = pos[balance];
			while (oldPos < newPos)
			{
				value[oldPos] += 1;
				oldPos += 1;
			}
			while (oldPos > newPos)
			{
				auto len = (posToSort[oldPos] -
				   posToSort[oldPos - 1]);
				value[oldPos] = 0;
				oldPos -= 1;
				res += value[oldPos] * len;
			}
			debug {writeln (value, " ", res, " ", balance);}
		}

		writeln (res);
	}
}


import std.stdio;
import std.math;
import std.numeric;
import std.container;
import std.typecons;
import core.stdc.stdio : scanf;
import std.conv;
import std.array;
import std.string;
import std.range;
import std.algorithm;

T read(T)() { return readln.chomp.to!T; }
T[] readarray(T)() { return readln.chomp.split(" ").map!(to!T).array; }

void solve() {
    int N, Q; readf("%d %d\n", &N, &Q);
    auto A = readarray!int;
    auto K = readarray!int;

    auto S = new int[N + 1];
    auto AS = new long[N + 1];
    for (int i = 0; i < N; i++) {
        S[i + 1] = max(S[i], A[i]);
        AS[i + 1] = AS[i] + A[i];
    }

    int[] ans;
    foreach (q; 0 .. Q) {
        int k = K[q];
        int lb = 0, ub = N;
        bool C(int x) {
            return S[x] <= k;
        }
        if (C(ub)) {
            ans ~= ub;
        } else {
            while (lb + 1 < ub) {
                int mid = (lb + ub) / 2;
                (C(mid) ? lb : ub) = mid;
            }
            ans ~= lb;
        }
    }
    writefln("%(%s %)", ans.map!(i => AS[i]).array);
}

void main() {
    int T = read!int;
    foreach (t; 0 .. T) solve();
}

import std.algorithm, std.array, std.container, std.conv, std.math, std.numeric, std.random, std.range, std.stdio, std.string, std.typecons, core.bitop;

void main()
{
  foreach (casenum ; 1 .. readln.strip.to!int + 1) {
    int n, q;
    readf!" %d %d "(n, q);
    auto a = readln.splitter.map!(to!long).array;
    auto qarr = readln.splitter.map!(to!long).array;
    long[] maxa;
    long[] suma;
    long m = 0;
    long sum = 0;
    suma ~= 0;
    foreach (x ; a) {
      m = max(m, x);
      maxa ~= m;
      sum += x;
      suma ~= sum;
    }
    writefln("%(%s %)", qarr.map!(k => suma[maxa.assumeSorted.lowerBound(k + 1).length]));
  }
}


import std.stdio;
import std.string;
import core.stdc.stdio;
import std.math;
import std.algorithm;

class Vec3
{
	public int x, y, z;
	public this()
	{
	}

	public this(int x, int y, int z)
	{
		this.x = x;
		this.y = y;
		this.z = z;
	}

	public Vec3 opBinary(string op)(Vec3 rhs)
	{
		static if (op == "+") return new Vec3(x + rhs.x, y + rhs.y, z + rhs.z);
		else static assert(0, "Operator "~op~" not implemented");
	}
}

int main(string[] argv)
{
	int n;
	scanf("%d", &n);
	Vec3 sum = new Vec3();
	foreach (int i; 0..n)
	{
		Vec3 v = new Vec3();
		scanf("%d %d %d", &(v.x), &(v.y), &(v.z));
		sum = sum + v;
	}
	bool condition = (sum.x == 0 && sum.y == 0 && sum.z == 0);
	printf(condition ? "YES" : "NO");
	return 0;
}

import std.stdio, std.string, std.algorithm, std.conv;

void main() {
    int n;
    readf("%s\n", &n);

    int[3] total;
    foreach(_; 0..n)
        total[] += to!(int[])(readln.split)[];

    if(any(total[]))
        writeln("NO");
    else
        writeln("YES");
}

import std.stdio;
import std.string;
import std.algorithm;
import std.conv;
import std.range;

void main() {
	int n = readln.chomp.to!int;

	int[] coord = [ 0, 0, 0 ];
	for (int i = 0; i < n; i++) {
		int[] row = readln.chomp.split.map!(to!int).array;
		coord[] += row[];
	}

	if (coord.all!("a == 0")) {
		"YES".writeln;
	} else {
		"NO".writeln;
	}
}

//prewritten code: https://github.com/antma/algo
module Solution;
import std.algorithm;
import std.array;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.traits;

final class InputReader {
  private:
  ubyte[] p, buffer;
  bool eof;
  bool rawRead () {
    if (eof) {
      return false;
    }
    p = stdin.rawRead (buffer);
    if (p.empty) {
      eof = true;
      return false;
    }
    return true;
  }
  ubyte nextByte(bool check) () {
    static if (check) {
      if (p.empty) {
        if (!rawRead ()) {
          return 0;
        }
      }
    }
    auto r = p.front;
    p.popFront ();
    return r;
  }
  public:
  this () {
    buffer = uninitializedArray!(ubyte[])(16<<20);
  }
  bool seekByte (in ubyte lo) {
    while (true) {
      p = p.find! (c => c >= lo);
      if (!p.empty) {
        return false;
      }
      if (!rawRead ()) {
        return true;
      }
    }
  }
  template next(T) if (isSigned!T) {
    T next ()  {
      if (seekByte (45)) {
        return 0;
      }
      T res;
      ubyte b = nextByte!false ();
      if (b == 45) {
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 - (b - 48);
        }
      } else {
        res = b - 48;
        while (true) {
          b = nextByte!true ();
          if (b < 48 || b >= 58) {
            return res;
          }
          res = res * 10 + (b - 48);
        }
      }
    }
  }
  template next(T) if (isUnsigned!T) {
    T next () {
      if (seekByte (48)) {
        return 0;
      }
      T res = nextByte!false () - 48;
      while (true) {
        ubyte b = nextByte!true ();
        if (b < 48 || b >= 58) {
          break;
        }
        res = res * 10 + (b - 48);
      }
      return res;
    }
  }
  T[] nextA(T) (in int n) {
    auto a = uninitializedArray!(T[]) (n);
    foreach (i; 0 .. n) {
      a[i] = next!T;
    }
    return a;
  }
}

void main() {
  auto r = new InputReader ();
  const n = r.next!uint;
  auto a = new int[3];
  foreach (tid; 0 .. n) {
    auto b = r.nextA!int (3);
    a[] += b[];
  }
  writeln (a.all!(i => i == 0) ? "YES" : "NO");
}


import std.algorithm;
import std.c.stdio;
import std.stdio;
import std.conv;

int curc;
bool eof = false;

void sb()
{
    do
    {
        curc = getchar ();
    }
    while (0 <= curc && curc <= 32);
    if (curc == EOF)
    {
        eof = true;
    }
}

char rc ()
{
    sb ();
    return cast (char) curc;
}

int ni ()
{
    sb ();
    int res = 0;
    do
    {
        res = res * 10 + cast (int) (curc - '0');
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

char[] ns ()
{
    sb ();
    char[] res = [];
    do
    {
        res ~= to!char(curc);
        curc = getchar ();
    }
    while (32 < curc);
    return res;
}

void CFBETA142A()
{
    class Tuple
    {
        int x, y;
        this(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        override string toString()
        {
            return to!string(this.x) ~ " " ~ to!string(this.y);
        }
    }

    auto s = ni();
    auto n = ni();
    bool ans = true;
    Tuple[] t = new Tuple[n];
    for (int i=0; i<n; ++i)
        t[i] = new Tuple(ni(), ni());
    sort!("a.x<b.x")(t);
    //write(t);
    int cursum = s;
    for (int i=0; i<n; ++i)
        if (t[i].x>=cursum) ans = false;
        else cursum+=t[i].y;
    printf(ans?"YES":"NO");
}

void main()
{
    CFBETA142A();
}

import std.stdio, std.string, std.algorithm , std.regex, std.conv, std.array;

void main()
{
    const auto readints = "stdin.readln.strip.split().map!(to!int).array";
    mixin("auto sn ="~readints~";");
    auto s=sn[0], n=sn[1];
    int[][] xys;
    foreach(i; 0..n) xys ~= [mixin(readints)];
    xys.sort!((a, b) => a[0] < b[0]);
    foreach (xy;xys){
        if (s<=xy[0]) { writeln("NO"); return;}
        s+=xy[1];
    }
    writeln("YES");
}

import std.stdio, std.string, std.conv, std.range, std.array, std.algorithm;
import std.uni, std.math, std.container, std.typecons, std.typetuple;
import core.bitop, std.datetime;

immutable int mod = 10^^9 + 7;

void main(){
    int s, n;
    readVars(s, n);
    auto x = new int[](n);
    auto y = new int[](n);

    foreach(i ; 0 .. n){
        readVars(x[i], y[i]);
    }

    sort(zip(x, y));

    //writeln(x);
    //writeln(y);

    foreach(i ; 0 .. n){
        if (s <= x[i]) {
            writeln("NO");
            return;
        }

        s += y[i];
    }

    writeln("YES");
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;

struct Dragon
{
	int health;
	int gain;
}

int main(string[] argv)
{
	int s, n;
	scanf("%d %d", &s, &n);
	Dragon[] dragons = new Dragon[n];
	foreach (int i; 0..n)
	{
		int x, y;
		scanf("%d %d", &x, &y);
		dragons[i].health = x;
		dragons[i].gain = y;
	}
	dragons.sort!("a.health < b.health");
	foreach (int i; 0..n)
	{
		if (s > dragons[i].health)
		{
			s += dragons[i].gain;
		} else {
			write("NO");
			return 0;
		}
	}
	write("YES");
	return 0;
}

// ab.d

import std.stdio;
import std.string;
import std.algorithm;
import std.regex;
import std.range;
import std.conv;
import std.array;

void main()
{
    const auto readints = "stdin.readln.strip.split(regex(` +`)).map!(to!int).array";
    mixin("auto sn ="~readints~";");
    auto s=sn[0], n=sn[1];
    int[][] xys;
    foreach(i; 0..n) xys ~= [mixin(readints)];
    xys.sort!((a, b) => a[0] < b[0]);
    foreach (xy;xys){
        //writeln(xy);
        //s-=xy[0];
        if (s<0) {
            writeln("NO");
            return;
        }
        s+=xy[1];
    }
    writeln("YES");
}

// ab.d

import std.stdio;
import std.string;
import std.algorithm;
import std.regex;
import std.range;
import std.conv;
import std.array;

void main()
{
    const auto readints = "stdin.readln.strip.split(regex(` +`)).map!(to!int).array";
    mixin("auto sn ="~readints~";");
    auto s=sn[0], n=sn[1];
    int[][] xys;
    foreach(i; 0..n) xys ~= [mixin(readints)];
    xys.sort!((a, b) => a[0] < b[0]);
    foreach (xy;xys){
        s-=xy[0];
        if (s<0) {
            writeln("NO");
            return;
        }
        s+=xy[1];
    }
    writeln("YES");
}

import std.stdio: writeln, stdin;
import std.string: strip;
import std.algorithm.iteration : map;
import std.regex;
import std.range;
import std.conv;

void main()
{
  auto sn = stdin.readln.strip.split(regex(` +`)).map!(to!int);
  auto s=sn[0], n=sn[1];

  for(int i = 1; i <= n; i++) {
    auto xy = stdin.readln.strip.split(regex(` +`)).map!(to!int);
    s-=xy[0];
    if (s<0) {
      writeln("NO");
      return;
    }
    s+=xy[1];
  }
  writeln("YES");
}

// ab.d

import std.stdio;
import std.string;
import std.algorithm;
import std.regex;
import std.range;
import std.conv;
import std.array;

void main()
{
    const auto readints = "stdin.readln.strip.split(regex(` +`)).map!(to!int).array";
    mixin("auto sn ="~readints~";");
    auto s=sn[0], n=sn[1];
    int[][] xys;
    foreach(i; 0..n) xys ~= [mixin(readints)];
    xys.sort!((a, b) => a[0] < b[0]);
    foreach (xy;xys){
        //writeln(xy);
        //s-=xy[0];
        if (s<xy[0]) {
            writeln("NO");
            return;
        }
        s+=xy[1];
    }
    writeln("YES");
}

import std.stdio;
import core.stdc.stdio;
import std.algorithm;

struct Dragon
{
	int health;
	int gain;
}

int main(string[] argv)
{
	int s, n;
	scanf("%d %d", &s, &n);
	Dragon[] dragons = new Dragon[n];
	foreach (int i; 0..n)
	{
		int x, y;
		scanf("%d %d", &x, &y);
		dragons[i].health = x;
		dragons[i].gain = y;
	}
	dragons.sort!("a.health < b.health");
	foreach (int i; 0..n)
	{
		if (s >= dragons[i].health)
		{
			s += dragons[i].gain;
		} else {
			write("NO");
			return 0;
		}
	}
	write("YES");
	return 0;
}