Codeforces Round #642 (Div. 3) A. Most Unstable Array
You are given two integers nn and mm . You have to construct the array aa of length nn consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly mm and the value ∑i=1n−1|ai−ai+1|∑i=1n−1|ai−ai+1| is the maximum possible. Recall that |x||x| is the absolute value of xx .
In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array a=[1,3,2,5,5,0]a=[1,3,2,5,5,0] then the value above for this array is |1−3|+|3−2|+|2−5|+|5−5|+|5−0|=2+1+3+0+5=11|1−3|+|3−2|+|2−5|+|5−5|+|5−0|=2+1+3+0+5=11 . Note that this example doesn't show the optimal answer but it shows how the required value for some array is calculated.
You have to answer tt independent test cases.
The first line of the input contains one integer tt (1≤t≤1041≤t≤104 ) — the number of test cases. Then tt test cases follow.
The only line of the test case contains two integers nn and mm (1≤n,m≤1091≤n,m≤109 ) — the length of the array and its sum correspondingly.
For each test case, print the answer — the maximum possible value of ∑i=1n−1|ai−ai+1|∑i=1n−1|ai−ai+1| for the array aa consisting of nn non-negative integers with the sum mm .
5 1 100 2 2 5 5 2 1000000000 1000000000 1000000000
0 2 10 1000000000 2000000000
挺有趣的思维水题。
可以注意到,n=1时答案为0,n=2时答案为m,n=3时整个差分之和不超过2*m,即答案为2*m.最大的情况就是0 a1 0 a2 0 a3...这么构造(a1+a2+a3..=m)或者0 0 0 m 0 0 0(m一定要放在中间)
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,m; cin>>n>>m; if(n==1) cout<<0<<endl; else if(n==2)cout<<m<<endl; else cout<<2*m<<endl; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!