Guess Game (Codeforces 1864E)
Tags: Math, games

Carol has a sequence $$$s$$$ of $$$n$$$ non-negative integers. She wants to play the "Guess Game" with Alice and Bob.To play the game, Carol will randomly select two integer indices $$$i_a$$$ and $$$i_b$$$ within the range $$$[1, n]$$$, and set $$$a=s_{i_a}$$$, $$$b=s_{i_b}$$$. Please note that $$$i_a$$$ and $$$i_b$$$ may coincide.Carol will tell:  the value of $$$a$$$ to Alice;  the value of $$$b$$$ to Bob;  the value of $$$a \mid b$$$ to both Alice and Bob, where $$$|$$$ denotes the bitwise OR operation. Please note that Carol will not tell any information about $$$s$$$ to either Alice or Bob.Then the guessing starts. The two players take turns making guesses, with Alice starting first. The goal of both players is to establish which of the following is true: $$$a < b$$$, $$$a > b$$$, or $$$a = b$$$.In their turn, a player can do one of the following two things:  say "I don't know", and pass the turn to the other player;  say "I know", followed by the answer "$$$a<b$$$", "$$$a>b$$$", or "$$$a=b$$$"; then the game ends. Alice and Bob hear what each other says, and can use this information to deduce the answer. Both Alice and Bob are smart enough and only say "I know" when they are completely sure.You need to calculate the expected value of the number of turns taken by players in the game. Output the answer modulo $$$998\,244\,353$$$.Formally, let $$$M = 998\,244\,353$$$. It can be shown that the answer can be expressed as an irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output the integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output such an integer $$$x$$$ that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$.

Input: Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^5$$$). The description of the test cases follows.The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 2\cdot 10^5$$$).The second line of each testcase contains $$$n$$$ integers $$$s_1,s_2,\ldots, s_n$$$ ($$$0 \le s_i < 2^{30}$$$).It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$. 

Output: For each test case, print a single integer — the answer to the problem modulo $$$998\,244\,353$$$.

Note: In the first test case, there are only $$$4$$$ possible situations:  $$$i_a=1$$$, $$$i_b=1$$$, $$$a=2$$$, $$$b=2$$$, the number of turns is $$$2$$$;  $$$i_a=1$$$, $$$i_b=2$$$, $$$a=2$$$, $$$b=3$$$, the number of turns is $$$3$$$;  $$$i_a=2$$$, $$$i_b=1$$$, $$$a=3$$$, $$$b=2$$$, the number of turns is $$$2$$$;  $$$i_a=2$$$, $$$i_b=2$$$, $$$a=3$$$, $$$b=3$$$, the number of turns is $$$3$$$. The expected number of turns is $$$\frac{2+3+2+3}{4}=\frac{5}{2}=499122179\pmod{998244353}$$$.Consider the first case, when $$$a=2$$$, $$$b=2$$$. The guessing process is as follows.In the first turn, Alice thinks, "I know that $$$a=2, a\mid b=2$$$. I can infer that $$$b=0$$$ or $$$b=2$$$, but I am not sure which one". Thus, she says, "I don't know".In the second turn, Bob thinks, "I know that $$$b=2, a\mid b=2$$$. I can infer that $$$a=0$$$ or $$$a=2$$$. But if $$$a=0$$$, then Alice would have already said that $$$a<b$$$ in the first turn, but she hasn't. So $$$a=2$$$". Thus, he says, "I know, $$$a=b$$$". The game ends. In the second test case, for $$$a=0$$$, $$$b=0$$$, Alice knows that $$$a=b$$$ immediately. The expected number of turns equals $$$1$$$.

Sample Inputs:
4
2
2 3
3
0 0 0
3
9 9 6
8
34124838 0 113193378 8 321939321 113193378 9463828 99

Sample Outputs:
499122179
1
332748120
77987843

Solution (Python):
""""""

def main():
    trie_address = [-1] * (2 * 200002 * 30)
    subtree_cnts = [0] * (2 * 200002 * 30)
    mod = 998244353
    t = int(input())
    allans = []
    for _ in range(t):
        j = 2
        n = int(input())
        s = readIntArr()
        for v in s:
            u = 0
            for i in range(29, -1, -1):
                if v & 1 << i == 0:
                    if trie_address[u] == -1:
                        trie_address[u] = j
                        j += 2
                    u = trie_address[u]
                else:
                    if trie_address[u + 1] == -1:
                        trie_address[u + 1] = j
                        j += 2
                    u = trie_address[u + 1]
                subtree_cnts[u] += 1
        ans = 0
        for v in s:
            a_turn = True
            n_turns = 1
            u = 0
            for i in range(29, -1, -1):
                if v & 1 << i == 0:
                    if trie_address[u + 1] != -1:
                        if a_turn:
                            ans += n_turns * subtree_cnts[trie_address[u + 1]] % mod
                            ans %= mod
                        else:
                            ans += (n_turns + 1) * subtree_cnts[trie_address[u + 1]] % mod
                            ans %= mod
                    u = trie_address[u]
                else:
                    if trie_address[u] != -1:
                        if a_turn:
                            ans += (n_turns + 1) * subtree_cnts[trie_address[u]] % mod
                            ans %= mod
                        else:
                            ans += n_turns * subtree_cnts[trie_address[u]] % mod
                            ans %= mod
                    a_turn = not a_turn
                    n_turns += 1
                    u = trie_address[u + 1]
            ans += n_turns * subtree_cnts[u] % mod
            ans %= mod
        denominator = n * n % mod
        ans = ans * pow(denominator, mod - 2, mod) % mod
        allans.append(ans)
        while j >= 0:
            trie_address[j] = -1
            subtree_cnts[j] = 0
            j -= 1
    multiLineArrayPrint(allans)
    return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
    dv = defaultValFactory
    da = dimensionArr
    if len(da) == 1:
        return [dv() for _ in range(da[0])]
    else:
        return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(a, b):
    print('? {} {}'.format(a, b))
    sys.stdout.flush()
    return int(input())

def answerInteractive(ans):
    print('! {}'.format(ans))
    sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
import math
for _abc in range(1):
    main()

Solution (Python):
""""""

def naive(a, b):

    def msb(x):
        for i in range(29, -1, -1):
            if x & 1 << i > 0:
                return i
        return -1
    ans = 1
    while True:
        if a == b == 0:
            return ans
        a_msb = msb(a)
        b_msb = msb(b)
        if a_msb < b_msb:
            return ans
        if a_msb > b_msb:
            return ans + 1
        a -= 1 << a_msb
        b -= 1 << b_msb
        (a, b) = (b, a)
        ans += 1
    return ans

def check_formula(a, b):
    if a == b:
        cnt = 1
        for i in range(30):
            if a & 1 << i > 0:
                cnt += 1
        return cnt
    cnt_a = 0
    for i in range(29, -1, -1):
        a_set = a & 1 << i > 0
        b_set = b & 1 << i > 0
        if a_set:
            cnt_a += 1
        if a_set != b_set:
            x = 0
            if a_set and (not b_set) and (cnt_a % 2 == 0):
                x = -1
            if not a_set and b_set and (cnt_a % 2 == 1):
                x = 1
            return 1 + cnt_a + x
mod = 998244353

def get_counts(a):
    n = len(a)
    a.sort()
    cnts = dict()
    c = 0
    for i in range(n):
        c += 1
        if i == n - 1 or a[i] != a[i + 1]:
            cnts[a[i]] = c
            c = 0
    return cnts

def solve(n, a):
    address = [-1, -1]
    subtree_size = [0, 0]
    cnts = get_counts(a)
    for v in a:
        i = 0
        for mask in range(29, -1, -1):
            if v & 1 << mask == 0:
                i2 = i
            else:
                i2 = i + 1
            if address[i2] == -1:
                address.extend([-1, -1])
                address[i2] = len(address) - 2
                subtree_size.extend([0, 0])
            i = address[i2]
            subtree_size[i] += 1
    total_moves = 0
    for v in a:
        cnt_a = 0
        i = 0
        for mask in range(29, -1, -1):
            a_is_set = v & 1 << mask
            if a_is_set:
                cnt_a += 1
            b_ways = x = 0
            if a_is_set:
                if address[i] != -1:
                    b_ways = subtree_size[address[i]]
                    if cnt_a % 2 == 0:
                        x = -1
                i = address[i + 1]
            else:
                if address[i + 1] != -1:
                    b_ways = subtree_size[address[i + 1]]
                    if cnt_a % 2 == 1:
                        x = 1
                i = address[i]
            total_moves += (1 + cnt_a + x) * b_ways % mod
            total_moves %= mod
        total_moves += (1 + cnt_a) * cnts[v] % mod
        total_moves %= mod
    denominator = n * n % mod
    ans = total_moves % mod * pow(denominator, mod - 2, mod) % mod
    return ans

def main():
    t = int(input())
    allans = []
    for _ in range(t):
        n = int(input())
        a = readIntArr()
        allans.append(solve(n, a))
    multiLineArrayPrint(allans)
    return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
    dv = defaultValFactory
    da = dimensionArr
    if len(da) == 1:
        return [dv() for _ in range(da[0])]
    else:
        return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(a, b):
    print('? {} {}'.format(a, b))
    sys.stdout.flush()
    return int(input())

def answerInteractive(ans):
    print('! {}'.format(ans))
    sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
import math
for _abc in range(1):
    main()

Solution (Python):
""""""

class Node:

    def __init__(self):
        self.L = None
        self.R = None
        self.subtree_cnts = 0

def main():
    mod = 998244353
    t = int(input())
    allans = []
    for _ in range(t):
        n = int(input())
        s = readIntArr()
        trie_address = [-1, -1]
        subtree_cnts = [0, 0]
        for v in s:
            u = 0
            for i in range(29, -1, -1):
                if v & 1 << i == 0:
                    if trie_address[u] == -1:
                        trie_address.extend([-1, -1])
                        trie_address[u] = len(trie_address) - 2
                        subtree_cnts.extend([0, 0])
                    u = trie_address[u]
                else:
                    if trie_address[u + 1] == -1:
                        trie_address.extend([-1, -1])
                        trie_address[u + 1] = len(trie_address) - 2
                        subtree_cnts.extend([0, 0])
                    u = trie_address[u + 1]
                subtree_cnts[u] += 1
        ans = 0
        for v in s:
            a_turn = True
            n_turns = 1
            u = 0
            for i in range(29, -1, -1):
                if v & 1 << i == 0:
                    if trie_address[u + 1] != -1:
                        if a_turn:
                            ans += n_turns * subtree_cnts[trie_address[u + 1]] % mod
                            ans %= mod
                        else:
                            ans += (n_turns + 1) * subtree_cnts[trie_address[u + 1]] % mod
                            ans %= mod
                    u = trie_address[u]
                else:
                    if trie_address[u] != -1:
                        if a_turn:
                            ans += (n_turns + 1) * subtree_cnts[trie_address[u]] % mod
                            ans %= mod
                        else:
                            ans += n_turns * subtree_cnts[trie_address[u]] % mod
                            ans %= mod
                    a_turn = not a_turn
                    n_turns += 1
                    u = trie_address[u + 1]
            ans += n_turns * subtree_cnts[u] % mod
            ans %= mod
        denominator = n * n % mod
        ans = ans * pow(denominator, mod - 2, mod) % mod
        allans.append(ans)
    multiLineArrayPrint(allans)
    return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
    print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
    print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
    print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
    return [int(x) for x in input().split()]

def makeArr(defaultValFactory, dimensionArr):
    dv = defaultValFactory
    da = dimensionArr
    if len(da) == 1:
        return [dv() for _ in range(da[0])]
    else:
        return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(a, b):
    print('? {} {}'.format(a, b))
    sys.stdout.flush()
    return int(input())

def answerInteractive(ans):
    print('! {}'.format(ans))
    sys.stdout.flush()
inf = float('inf')
from math import gcd, floor, ceil
import math
for _abc in range(1):
    main()