Table of Contents

ExplanationImplementation

Explanation

Notice that we're asked to count the total number of paths, so we can store the graph as an adjacency matrix by setting Ai,j=1A_{i, j}=1 if the number of bits xixjx_i \oplus x_j is divisible by 33. After constructing these edges, notice that this is the same problem as CSES - Graph Paths(solution), except we query the sum of all the paths.

Then, we can calculate AkA^k in O(N3logK)\mathcal{O}(N^3\log K) using Matrix Exponentiation.

Our final answer is:

i=0Nj=0NAi,jk\sum_{i=0}^N \sum_{j=0}^N A_{i, j}^k

Implementation

Time Complexity: O(N3logK)\mathcal{O}(N^3\log K)

C++

#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
template <class T> struct Matrix {
vector<vector<T>> v;
void init(int n, int m) { v = vector<vector<T>>(n, vector<T>(m)); }
Matrix operator*(Matrix b) {

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!