\[\begin{eqnarray*}
&&\sum_{i=0}^{n-1}\left (ki+b-a_i\right) ^2\\
&=&\sum_{i=0}^{n-1}\left (k^2i^2+b^2+a_i^2+2kbi-2kia_i-2ba_i\right) \ \
&=&k^2\sum_{i=0}^{n-1}i^2+nb^2+\sum_{i=0}^{n-1}a_i^2+2kb\sum_{i=0}^{n-1}i-2k\sum_{i=0}^{n-1}ia_i-2b\ Sum_{i=0}^{n-1}a_i\\
\end{eqnarray*}\]
Set
\[\begin{eqnarray*}
a&=&\sum_{i=0}^{n-1}i^2\\
B&=&\sum_{i=0}^{n-1}i\\
C&=&\sum_{i=0}^{n-1}ia_i\\
D&=&\sum_{i=0}^{n-1}a_i\\
\end{eqnarray*}\]
You only need to minimize
\[\begin{eqnarray*}
&&ak^2+nb^2+2kbb-2kc-2db\\
&=&nb^2+ (2kb-2d) b+ak^2-2kc\\
\end{eqnarray*}\]
This is a two-time function on $b$, obviously when $b$ takes $\frac{d-kb}{n}$ to get the minimum value, $b$ is expressed in $k$, then
\[\begin{eqnarray*}
&&ak^2+nb^2+2kbb-2kc-2db\\
&=&ak^2+\frac{\left (d-kb\right) ^2}{n}+\frac{2kb\left (d-kb\right)}{n}-2kc-\frac{2d\left (D-kB\right)}{n} \\
&=&ak^2+\frac{-d^2-b^2k^2+2bdk}{n}-2ck\\
&=&\frac{nak^2-2nck-d^2-b^2k^2+2bdk}{n}\\
&=&\frac{\left (na-b^2\right) k^2+\left (2bd-2nc\right) k-d^2}{n}\\
\end{eqnarray*}\]
This is also a two-time function on $k$, which obviously gets the minimum value when $k$ takes $\frac{nc-bd}{na-b^2}$. Direct calculation, time complexity $o (n) $.
#include <cstdio>int n,i,j;double a,b,c,d,k,b;inline void Read (Int&a) { char c;bool f=0;a=0; while (!) ( (((C=getchar ()) >= ' 0 ') && (c<= ' 9 ')) | | (c== '-'))); if (c!= '-') a=c-' 0 '; else f=1; while ((C=getchar ()) >= ' 0 ') && (c<= ' 9 ')) (a*=10) +=c-' 0 '; if (f) a=-a;} int main () { for (read (n); i<n;i++) Read (j), A+=1.0*i*i,b+=i,c+=1.0*i*j,d+=j; k= (c*n-b*d)/(A*n-b*b), b= (d-k*b)/n; return printf ("%.7f%.7f", b,k), 0;}
BZOJ3095: Two tuples