PROBLEM LINK:
Author: Konstantsin Sokol
Tester: Gedi Zheng
Editorialist: Miguel Oliveira
DIFFICULTY:
Easy.
PREREQUISITES:
Math, Linear Algebra.
PROBLEM
We have a system of N equations on N variables. Equation i is of the form: x_1 + x_2 + ... + x_{i-1} + x_{i+1} + .. x_n = A_i. You can prove that solution of this system of equations will be unique. You have to solve this system of equations.
QUICK EXPLANATION
- Write each equation in form of sum - x_i = A_i where sum denotes sum of all the variables i.e. sum = x_1 + x_2 + \dots + x_n. So, x_i = (sum - A_i)
- Now only thing that we have to do is to compute value of sum in terms of known values A_1, A_2, \dots A_n.
Let us add all the equations, we get N * sum - ( x_1 + x_2 + \dots + x_n) = A_1 + A_2 + \dots + A_n.
As, sum = x_1 + x_2 + \dots + x_n, we get sum = \frac{A_1 + A_2 + \dots + A_n}{N - 1} - So finally, x_i = \frac{A_1 + A_2 + \dots + A_n}{N - 1} - A_i.
EXPLANATION
The solution to a system of 2 variables is trivial:
\begin{cases} x_2 = A_1 \\ x_1 = A_2 \end{cases}
If we have 3 variables, the system is:
\begin{cases} x_2 + x_3 = A_1 \\ x_1 + x_3 = A_2 \\ x_1 + x_2 = A_3 \end{cases}
Each variable appears N-1 times. Let’s sum these equations. We get
\begin{array}{lcl} 2 * x_1 + 2 * x_2 + 2 * x_3 & = & A_1 + A_2 + A_3 \\ 2 * (x_1 + x_2 + x_3) & = & A_1 + A_2 + A_3 \\ x_1 + x_2 + x_3 & = & \frac{A_1 + A_2 + A_3}{2} \end{array}
Now, to know the value of each variable, we can reuse the original equations. Then, to know the value of x1, we can use the fact that x_2 + x_3 = A_1. Let S = A_1 + A_2 + A_3, then x_1 + A_1 = \frac{S}{2} \Leftrightarrow x_1 = \frac{S}{2} - A_1.
In general, let S = A_1 + A_2 + ... + A_n. For each variable, x_i = \frac{S}{N-1} - A_i.
Time Complexity
We can compute the sum in linear time and calculate the answer in linear time as well for a O(N) solution.