9. (16 points) When $x \geqslant 0$, find the minimum value $g(a)$ of the function
$$
f(x)=2 x+(|x-1|-a)^{2}
$$


9. Note that,
$$
\begin{array}{c}
f(x)=2 x+(|x-1|-a)^{2} \\
=x^{2}-2 a|x-1|+a^{2}+1 .
\end{array}
$$
(1) $a>1$.
(i) When $x \geqslant 1$,
$$
f(x)=x^{2}-2 a x+a^{2}+2 a+1
$$

is decreasing on $[1, a]$ and increasing on $[a,+\infty)$, thus,
$$
f(x)_{\min }=2 a+1 \text {. }
$$
(ii) When $0 \leqslant x \leqslant 1$,
$$
f(x)=x^{2}+2 a x+a^{2}-2 a+1
$$

is increasing on $[0,1]$, thus,
$$
f(x)_{\text {min }}=a^{2}-2 a+1 .
$$

And $a^{2}-2 a+1-(2 a+1)=a^{2}-4 a$, so when $14$, $g(a)=2 a+1$.
(2) $0 \leqslant a \leqslant 1$.
(i) When $x \geqslant 1$,
$$
f(x)=x^{2}-2 a x+a^{2}+2 a+1
$$

is increasing on $[1,+\infty)$, thus,
$$
f(x)_{\min }=a^{2}+2 \text {. }
$$
(ii) When $0 \leqslant x \leqslant 1$,
$$
f(x)=x^{2}+2 a x+a^{2}-2 a+1
$$

is increasing on $[0,1]$, thus,
$$
f(x)_{\text {min }}=a^{2}-2 a+1 .
$$

And $a^{2}-2 a+1-\left(a^{2}+2\right)=-1-2 a<0$, so
$$
g(a)=a^{2}-2 a+1 \text {. }
$$
(3) $-1<a<0$.
(i) When $x \geqslant 1$,
$$
f(x)=x^{2}-2 a x+a^{2}+2 a+1
$$

is increasing on $[1,+\infty)$, thus,
$$
f(x)_{\text {min }}=a^{2}+2 \text {; }
$$
(ii) When $0 \leqslant x \leqslant 1$,
$$
f(x)=x^{2}+2 a x+a^{2}-2 a+1
$$

is increasing on $[0,-a]$ and decreasing on $[-a, 1]$, thus,
$$
f(x)_{\text {min }}=-2 a+1 .
$$

And $a^{2}+2-(-2 a+1)=a^{2}+2 a+1 \geqslant 0$, so
$$
g(a)=-2 a+1 \text {. }
$$
(4) $a \leqslant-1$.
(i) When $x \geqslant 1$,
$$
f(x)=x^{2}-2 a x+a^{2}+2 a+1
$$

is increasing on $[1,+\infty)$, thus,
$$
f(x)_{\text {min }}=a^{2}+2 \text {. }
$$
(ii) When $0 \leqslant x \leqslant 1$,
$$
f(x)=x^{2}+2 a x+a^{2}-2 a+1
$$

is decreasing on $[0,1]$, thus,
$$
f(x)_{\text {min }}=a^{2}+2 .
$$

So $g(a)=a^{2}+2$.
In summary, $g(a)=\left\{\begin{array}{ll}2 a+1, & a \geqslant 4 ; \\ a^{2}-2 a+1, & 0 \leqslant a<4 ; \\ 1-2 a, & -1<a<0 ; \\ a^{2}+2, & a \leqslant-1 .\end{array}\right.$