Heavy oil with a high pour point and high viscosity is transported in a heated oil pipeline with many oil pumping and heating stations. Electricity and fuel costs account for a large share of total pumping cost. Minimizing the total operating cost of pumps and heating furnaces used to pump oil requires optimization of their hydrodynamic parameters, and, above all, the distribution of pressure and temperature along the pipeline. The application of graph theory and dynamic programming to determine the problem of the global optimum of energy consumption is given in a heated oil pipeline with many oil pumping and heating stations. The problem of mass and heat transport was solved numerically. The results of the optimization problem were applied to a digital section of a heated trunk interstate oil pipeline 450 km long. The results of thermohydraulic calculations were consistent with the actual data of the Supervisory Control and Data Acquisition (SCADA) system. Energy saving is 38.9 % in the optimal regime.