Most Unstable Array CodeForces - 1353A(数学+贪心+建设性算法)

题意:

给定 n, m,构造出一个长度为 n 的数组 a,使得数组的和为 m,在此条件下 ∑ i = 1 n − 1 ∣ a i − a i − 1 ∣ \sum_{i=1}^{n-1}|a_{i}−a_{i-1}| i=1n1aiai1 最大是多少?

题目:

You are given two integers n and m. You have to construct the array a of length n 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 m and the value ∑ i = 1 n − 1 ∣ a i − a i − 1 ∣ \sum_{i=1}^{n-1}|a_{i}−a_{i-1}| i=1n1aiai1 is the maximum possible. Recall that |x| is the absolute value of x.

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] then the value above for this array is |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 t independent test cases.

Input

The first line of the input contains one integer t (1≤t≤104) — the number of test cases. Then t test cases follow.

The only line of the test case contains two integers n and m (1≤n,m≤109) — the length of the array and its sum correspondingly.

Output

For each test case, print the answer — the maximum possible value of ∑ i = 1 n − 1 ∣ a i − a i − 1 ∣ \sum_{i=1}^{n-1}|a_{i}−a_{i-1}| i=1n1aiai1 for the array a consisting of n non-negative integers with the sum m.

Example

Input

5
1 100
2 2
5 5
2 1000000000
1000000000 1000000000

Output

0
2
10
1000000000
2000000000

Note

In the first test case of the example, the only possible array is [100] and the answer is obviously 0.

In the second test case of the example, one of the possible arrays is [2,0] and the answer is |2−0|=2.

In the third test case of the example, one of the possible arrays is [0,2,0,3,0] and the answer is |0−2|+|2−0|+|0−3|+|3−0|=10.

思维:

挺有趣的思维水题。
可以注意到,n=1时答案为0,n=2时答案为m,n=3时整个差分之和不超过2m,即答案为2m.最大的情况就是0 a1 0 a2 0 a3…这么构造(a1+a2+a3…=m)或者0 0 0 m 0 0 0(m一定要放在中间)

AC代码

#include<stdio.h>
#include<string.h>
int t,n,m;
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        if(n==1)printf("0\n");
        else if(n==2)printf("%d\n",m);
        else printf("%d\n",2*m);
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值