Xor-matic Number of the Graph (Codeforces 724G)
Tags: Math, bitmasks

You are given an undirected graph, constisting of n vertices and m edges. Each edge of the graph has some non-negative integer written on it.Let's call a triple (u, v, s) interesting, if 1 ≤ u < v ≤ n and there is a path (possibly non-simple, i.e. it can visit the same vertices and edges multiple times) between vertices u and v such that xor of all numbers written on the edges of this path is equal to s. When we compute the value s for some path, each edge is counted in xor as many times, as it appear on this path. It's not hard to prove that there are finite number of such triples.Calculate the sum over modulo 109 + 7 of the values of s over all interesting triples.

Input: The first line of the input contains two integers n and m (1 ≤ n ≤ 100 000, 0 ≤ m ≤ 200 000) — numbers of vertices and edges in the given graph.The follow m lines contain three integers ui, vi and ti (1 ≤ ui, vi ≤ n, 0 ≤ ti ≤ 1018, ui ≠ vi) — vertices connected by the edge and integer written on it. It is guaranteed that graph doesn't contain self-loops and multiple edges.

Output: Print the single integer, equal to the described sum over modulo 109 + 7.

Note: In the first example the are 6 interesting triples:   (1, 2, 1)  (1, 3, 2)  (1, 4, 3)  (2, 3, 3)  (2, 4, 2)  (3, 4, 1)  The sum is equal to 1 + 2 + 3 + 3 + 2 + 1 = 12.In the second example the are 12 interesting triples:   (1, 2, 1)  (2, 3, 2)  (1, 3, 3)  (3, 4, 4)  (2, 4, 6)  (1, 4, 7)  (1, 4, 8)  (2, 4, 9)  (3, 4, 11)  (1, 3, 12)  (2, 3, 13)  (1, 2, 14)  The sum is equal to 1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 + 11 + 12 + 13 + 14 = 90.

Sample Inputs:
4 4
1 2 1
1 3 2
2 3 3
3 4 1

4 4
1 2 1
2 3 2
3 4 4
4 1 8

8 6
1 2 2
2 3 1
2 4 4
4 5 5
4 6 3
7 8 5

Sample Outputs:
12

90

62

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def make_graph(n, m):
    (x, y, s) = ([0] * (2 * m), [0] * (2 * m), [0] * (n + 3))
    for i in range(0, 2 * m, 2):
        (u, v, w) = map(int, input().split())
        s[u + 2] += 1
        s[v + 2] += 1
        (x[i], x[i + 1], y[i], y[i + 1]) = (u, v, w, w)
    for i in range(3, n + 3):
        s[i] += s[i - 1]
    (G, W) = ([0] * (2 * m), [0] * (2 * m))
    for i in range(2 * m):
        j = x[i] + 1
        (G[s[j]], W[s[j]]) = (x[i ^ 1], y[i])
        s[j] += 1
    return (G, W, s)

def bfs(s):
    (q, k) = ([s], 0)
    dist[s] = 0
    b = []
    while len(q) ^ k:
        i = q[k]
        di = dist[i]
        for v in range(s0[i], s0[i + 1]):
            (j, w) = (G[v], W[v])
            if dist[j] == -1:
                dist[j] = di ^ w
                q.append(j)
            else:
                u = dist[j] ^ di ^ w
                for b0 in b:
                    u = min(u, u ^ b0)
                if u:
                    b.append(u)
        k += 1
    if not b:
        b = [0]
    return (q, b)
(n, m) = map(int, input().split())
mod = pow(10, 9) + 7
(G, W, s0) = make_graph(n, m)
dist = [-1] * (n + 1)
pow2 = [1]
for _ in range(60):
    pow2.append(2 * pow2[-1])
ans = 0
inv2 = pow(2, mod - 2, mod)
for i in range(1, n + 1):
    if dist[i] ^ -1:
        continue
    (p, b) = bfs(i)
    m = len(p)
    x = pow2[len(b) - 1] % mod * m % mod * (m - 1) % mod * inv2 % mod
    l = 1 if b[0] == 0 else pow2[len(b)] % mod
    v = 0
    for j in b:
        v |= j
    for j in pow2:
        if v & j:
            ans += x * j % mod
        else:
            c = 0
            for k in p:
                if dist[k] & j:
                    c += 1
            ans += c * (m - c) % mod * j % mod * l % mod
ans %= mod
print(ans)

Solution (Python):
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def make_graph(n, m):
    (x, y, s) = ([0] * (2 * m), [0] * (2 * m), [0] * (n + 3))
    for i in range(0, 2 * m, 2):
        (u, v, w) = map(int, input().split())
        s[u + 2] += 1
        s[v + 2] += 1
        (x[i], x[i + 1], y[i], y[i + 1]) = (u, v, w, w)
    for i in range(3, n + 3):
        s[i] += s[i - 1]
    (G, W) = ([0] * (2 * m), [0] * (2 * m))
    for i in range(2 * m):
        j = x[i] + 1
        (G[s[j]], W[s[j]]) = (x[i ^ 1], y[i])
        s[j] += 1
    return (G, W, s)

def bfs(s):
    (q, k) = ([s], 0)
    dist[s] = 0
    b = []
    while len(q) ^ k:
        i = q[k]
        di = dist[i]
        for v in range(s0[i], s0[i + 1]):
            (j, w) = (G[v], W[v])
            if dist[j] == -1:
                dist[j] = di ^ w
                q.append(j)
            else:
                u = dist[j] ^ di ^ w
                for b0 in b:
                    u = min(u, u ^ b0)
                if u:
                    b.append(u)
        k += 1
    if not b:
        b = [0]
    return (q, b)
(n, m) = map(int, input().split())
mod = pow(10, 9) + 7
(G, W, s0) = make_graph(n, m)
dist = [-1] * (n + 1)
pow2 = [1]
for _ in range(60):
    pow2.append(2 * pow2[-1])
ans = 0
inv2 = pow(2, mod - 2, mod)
for i in range(1, n + 1):
    if dist[i] ^ -1:
        continue
    (p, b) = bfs(i)
    m = len(p)
    x = pow2[len(b) - 1] % mod * m % mod * (m - 1) % mod * inv2 % mod
    l = 1 if b[0] == 0 else pow2[len(b)] % mod
    v = 0
    for j in b:
        v |= j
    for j in pow2:
        if v & j:
            ans += x * j % mod
        else:
            c = 0
            for k in p:
                if dist[k] & j:
                    c += 1
            ans += c * (m - c) % mod * j % mod * l % mod
ans %= mod
print(ans)

Solution (Python):
from io import BytesIO, IOBase
import sys
import os
import bisect
import math
import random
from collections import Counter, defaultdict, deque
from copy import deepcopy
from functools import cmp_to_key, lru_cache, reduce
from heapq import heapify, heappop, heappush, heappushpop, nlargest, nsmallest
from itertools import accumulate, combinations, permutations, count, product
from operator import add, iand, ior, itemgetter, mul, xor
from string import ascii_lowercase, ascii_uppercase
from typing import *

class IOWrapper(IOBase):

    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode('ascii'))
        self.read = lambda : self.buffer.read().decode('ascii')
        self.readline = lambda : self.buffer.readline().decode('ascii')
BUFSIZE = 5096

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = 'x' in file.mode or 'r' not in file.mode
        self.write = self.buffer.write if self.writable else None

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b'\n') + (not b)
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            (self.buffer.truncate(0), self.buffer.seek(0))

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
        self.newlines = 0
        return self.buffer.read()
sys.stdin = IOWrapper(sys.stdin)
sys.stdout = IOWrapper(sys.stdout)
input = lambda : sys.stdin.readline().rstrip('\r\n')

def I():
    return input()

def II():
    return int(input())

def MII():
    return map(int, input().split())

def LI():
    return list(input().split())

def LII():
    return list(map(int, input().split()))

def GMI():
    return map(lambda x: int(x) - 1, input().split())

def LGMI():
    return list(map(lambda x: int(x) - 1, input().split()))
inf = float('inf')

class XorBase:
    n = 30

    def __init__(self):
        self.base = [0] * self.n

    def add(self, num):
        for i in range(num.bit_length() - 1, -1, -1):
            if num >> i & 1:
                if self.base[i] == 0:
                    self.base[i] = num
                    return
                else:
                    num ^= self.base[i]

    def check(self, num):
        for i in range(num.bit_length() - 1, -1, -1):
            if num >> i & 1:
                if self.base[i] == 0:
                    return False
                num ^= self.base[i]
        return True

    def realBase(self):
        for i in range(self.n):
            for j in range(i - 1, -1, -1):
                if self.base[i] ^ self.base[j] < self.base[i]:
                    self.base[i] ^= self.base[j]
        return [val for val in self.base if val]

    def maxVal(self):
        ans = 0
        for i in range(self.n - 1, -1, -1):
            if ans ^ base[i] > ans:
                ans ^= base[i]
        return ans

    def merge(base1, base2):
        res = XorBase()
        for val in base1.base:
            if val:
                res.add(val)
        for val in base2.base:
            if val:
                res.add(val)
        return res
XorBase.n = 60
(n, m) = MII()
path = [[] for _ in range(n)]
for _ in range(m):
    (u, v, w) = MII()
    u -= 1
    v -= 1
    path[u].append((v, w))
    path[v].append((u, w))
mod = 10 ** 9 + 7
pow_2 = [(1 << i) % mod for i in range(60)]
vis = [1 << 60] * n
ans = 0
for i in range(n):
    if vis[i] == 1 << 60:
        cnt = 1
        vis[i] = 0
        stack = [i]
        base = XorBase()
        note = [i]
        while stack:
            u = stack.pop()
            for (v, w) in path[u]:
                if vis[v] == 1 << 60:
                    vis[v] = vis[u] ^ w
                    cnt += 1
                    stack.append(v)
                    note.append(v)
                else:
                    base.add(vis[v] ^ vis[u] ^ w)
        real_base = base.realBase()
        length = len(real_base)
        for i in range(60):
            c0 = c1 = 0
            for x in note:
                if vis[x] >> i & 1:
                    c1 += 1
                else:
                    c0 += 1
            flag = False
            for v in real_base:
                if v >> i & 1:
                    flag = True
                    break
            if flag:
                ans += (c0 * c1 * pow_2[length - 1] + (c0 * (c0 - 1) // 2 + c1 * (c1 - 1) // 2) * pow_2[length - 1]) % mod * pow_2[i]
            else:
                ans += c0 * c1 * pow_2[length] % mod * pow_2[i]
            ans %= mod
print(ans)