Answer. (n+1)n2.
Solution. Introduce a coordinate system so that the centers of the cubes have coordinates from 1 to 3n along each axis. Assign each cube the coordinates of its center. Thus, a cube is black if and only if all its coordinates give a remainder of 2 when divided by 3.
Paint red all white cubes with coordinates (a,b,c), where a is divisible by 3, and b≡c≡2(mod3), as well as all cubes with coordinates (1,b,c), where b≡c≡2(mod3). It is easy to see that this results in (n+1)n2 red cubes, and the problem's requirements are met. It remains to show that the required result cannot be achieved by painting fewer than (n+1)n2 cubes.
For i=1,2,…,n set w3i=i,w3i−1=0,w3i−2= =n+1−i; the sequence (wi) looks like this: n,0,1,n− −1,0,2,n−2,…,1,0,n. Write the number wawbwc in each cube with coordinates (a,b,c) (in particular, zeros are written in black cubes). Then the total sum of all numbers written in white cubes will be Σ=(w1+…+w3n)3=n3(n+1)3.
Let the cost S(X) of a cube X be the sum of the numbers in all cubes that share a vertex with it (including X itself). Then, in any coloring that satisfies the requirements, the sum of the costs of the red cubes is not less than Σ. We will now prove that S(X)⩽(n+1)2n for any white cube X. From this it follows that at least (n+1)2nΣ=(n+1)n2 cubes must be painted red, as required.
Let (a,b,c) be the coordinates of the cube X. The abscissas of all cubes that share a vertex with it are equal to a or a±1; the same statement is true for the other coordinates. Therefore, S(X)=(wa−1+wa+wa+1)(wb−1+wb+wb+1)(wc−1+wc+ +wc+1), where we set w0=w3n+1=0. It remains to note that wt−1+wt+wt+1=n if t≡2(mod3), and wt−1+wt+wt+1=n+1 otherwise. Since not all coordinates of X give a remainder of 2, it follows that S(X)⩽(n+1)2n.