Inference and Optimization over Networks: Communication Efficiency and Optimality