题解:AtCoder AT_awc0004_c Minimum Cost of Temperature Adjustment
本文分享的必刷题目是从蓝桥云课、洛谷、AcWing等知名刷题平台精心挑选而来并结合各平台提供的算法标签和难度等级进行了系统分类。题目涵盖了从基础到进阶的多种算法和数据结构旨在为不同阶段的编程学习者提供一条清晰、平稳的学习提升路径。欢迎大家订阅我的专栏算法题解C与Python实现附上汇总贴算法竞赛备考冲刺必刷题C | 汇总【题目来源】AtCoderC - Minimum Cost of Temperature Adjustment【题目描述】Takahashi is going to conduct a chemistry experiment.高桥将要进行一项化学实验。In this experiment, he needs to process allN NNreagents, each exactly once. The processing temperature of reagenti ii( 1 ≤ i ≤ N ) (1 \leq i \leq N)(1≤i≤N)isH i H_iHidegrees.在此实验中他需要处理全部N NN种试剂每种试剂恰好处理一次。试剂i ii1 ≤ i ≤ N 1 ≤ i ≤ N1≤i≤N的处理温度为H i H_iHi度。The temperature of the experimental apparatus is initially set to0 00degrees. To process a reagent, the apparatus temperature must be set to exactly match the processing temperature of that reagent. Takahashi can freely choose the order in which to process the reagents. After processing all reagents, he must return the apparatus temperature to0 00degrees to finish the experiment.实验仪器的初始温度设定为0 00度。要处理一种试剂仪器温度必须被设定为恰好匹配该试剂的处理温度。高桥可以自由选择处理试剂的顺序。处理完所有试剂后他必须将仪器温度调回0 00度以结束实验。When changing the apparatus temperature froma aadegrees tob bbdegrees, the energy consumption is∣ a − b ∣ |a - b|∣a−b∣.当将仪器温度从a aa度改变到b bb度时能量消耗为∣ a − b ∣ |a - b|∣a−b∣。If the order of processing the reagents is( p 1 , p 2 , … , p N ) (p_1, p_2, \ldots, p_N)(p1,p2,…,pN)(a permutation of( 1 , 2 , … , N ) (1, 2, \ldots, N)(1,2,…,N)), the total energy consumption is如果处理试剂的顺序为( p 1 , p 2 , … , p N ) (p_1, p_2, …, p_N)(p1,p2,…,pN)即( 1 , 2 , … , N ) (1, 2, …, N)(1,2,…,N)的一个排列则总能量消耗为∣ H p 1 ∣ ∣ H p 2 − H p 1 ∣ ⋯ ∣ H p N − H p N − 1 ∣ ∣ H p N ∣ |H_{p_1}| |H_{p_2} - H_{p_1}| \cdots |H_{p_N} - H_{p_{N-1}}| |H_{p_N}|∣Hp1∣∣Hp2−Hp1∣⋯∣HpN−HpN−1∣∣HpN∣Here, the first term corresponds to the cost of changing from the initial0 00degrees to the processing temperature of the first reagent, and the last term corresponds to the cost of returning from the processing temperature of the last reagent to0 00degrees.此处第一项对应于从初始0 00度改变到第一种试剂处理温度的成本最后一项对应于从最后一种试剂的处理温度调回0 00度的成本。Takahashi wants to minimize the total energy consumption by optimally choosing the order in which to process the reagents. Find the minimum total energy consumption.高桥希望通过最优选择处理试剂的顺序来最小化总能量消耗。求最小总能量消耗。【输入】N NNH 1 H_1H1H 2 H_2H2⋯ \cdots⋯H N H_NHNThe first line contains an integerN NN, representing the number of reagents.The second line containsN NNintegersH 1 , H 2 , … , H N H_1, H_2, \ldots, H_NH1,H2,…,HNseparated by spaces, representing the processing temperature of each reagent.【输出】Output the minimum total energy consumption as an integer on a single line.【输入样例】3 5 -3 2【输出样例】16【解题思路】【算法标签】#贪心#【代码详解】#includebits/stdc.husingnamespacestd;#defineintlonglongconstintN200005;intn;// 数据个数inth[N],ans;// h: 高度数组ans: 总距离signedmain(){cinn;// 读入数据个数for(inti1;in;i){cinh[i];// 读入高度}sort(h1,hn1);// 对高度进行排序// 计算相邻元素间的绝对差值之和// 注意这里循环到n1h[0]默认是0for(inti1;in1;i){ansabs(h[i]-h[i-1]);// 累加绝对差值}coutansendl;// 输出总距离return0;}【运行结果】3 5 -3 2 16