From the question, the distance between #p# and #r#, by Pythagoras, is #sqrt[x^2+9]# and the distance between #r# and #q# is #sqrt[[5-x]^2+16]#.
So the total cost #C# is will be #2[sqrt[x^2+9]]^2# +#3[sqrt[[5-x^2]+16]]^2#, this because the question tell us that the cost is dependent on the ' square' of the distance, and the 'square' of square root of a function is just the function. e.g, #[sqrt a]^2#=#a#.
Thus we have #C# =#2[x^2+9]# + #3[[5-x]^2+16]# and expanding the brackets in the expression,
#C# =#2x^2+18 #+ #3[25-10x+x^2+16]#,
=#2x^2+18+75-30x+3x^2+48#, and collecting like terms gives the expression in the question. Hope this helps.