0

I am solving this question from a contest on codeforces. How to solve this. Can we get any recurrence relation or generalized solution for this question?

What I have understood is we have to find

$$3\mid a_1+a_2+a_3+....+a_n$$ where $-1 < a_i < k$ for all $0 < i < (n+1)$ where $k$ is any positive integer.

Question link :http://codeforces.com/contest/1105/problem/C

2 Answers2

2

Hint: For integers $l\le r$, $n\ge 0$, $c\in\{0,1,2\}$, let $f(l,r,n,c)$ be the number of arrays of $n$ integers $\in\{l,\ldots, r\}$ such that their sum is $\equiv c\pmod 3$. Now try to express $f(l,r,n,c)$ in terms of the $f(l,r,n-1,*)$.

0

I am answering the question as posted, where $0\le a_i <k$, not the original coding challenge, where the constraint is $l\le a_i\le r$. However, using the transformation $a_i\to a_i-l$, you should be able to turn the latter problem into the former.


Suppose first that $k=3j$ is a multiple of three. The number of ways to choose numbers $a_i$ so that $-1<a_i<k$ is $(3j)^n$. I claim that exactly one third of these solutions have $\sum a_i$ a multiple of $3$. Indeed, if you break solutions into triplets like $$ (3i,a_2,a_3,\dots,a_n),(3i+1,a_2,a_3,\dots,a_n),(3i+2,a_2,a_3,\dots,a_n) $$ then exactly one solution in each triplet has a sum which is a multiple of $3$. Therefore, the number of vectors is $$ \frac13 k^n $$

The problem is easy when $k=3j$. What about when $k=3j+1$? A similarly argument shows that among vectors $(a_1,\dots,a_n)$ where at least one coordinate is unequal to $3j$, exactly one third of them have sum which is a multiple of $3$. The only remaining vector is where every $a_i=3j$, whose sum $3$ divides. Therefore, the number of vectors is $$ \frac13[k^n-1]+1 $$ Note that these numbers can be computed pretty much instantly, no recursion needed!

Finally, the hardest case is when $k=3j+2$. Among the $k^n-2^n$ solutions where at least one $a_i$ is less than $3j$, exactly one third of these have sum a multiple of $3$. The remaining $2^n$ vectors have coordinates all of the form $3j+b$, where $b\in \{0,1\}$. Furthermore, the sum will be a multiple of three if and only if the number of $i$ for which $a_i=3j+1$ is a multiple of $3$. So the question becomes...

Given a number $n$, how many of the $2^n$ subsets of $\{1,2,\dots,n\}$ have a size which is a multiple of $3$?

For that, I point you to How do I count the subsets of a set whose number of elements is divisible by 3? 4?.

Mike Earnest
  • 75,930