ACdream群训练赛(38) / J - Positive Negative Sign

J - Positive Negative Sign


Time Limit: 2000 MS      Memory Limit: 32768 KB      64bit IO Format: unknown

Description

Given two integers: n and m and n is divisible by 2m, you have to write down the first n natural numbers in the following form. At first take first m integers and make their sign negative, then take next m integers and make their sign positive, the next m integers should have negative signs and continue this procedure until all the n integers have been assigned a sign. For example, let n be 12 and m be 3. Then we have

-1 -2 -3 +4 +5 +6 -7 -8 -9 +10 +11 +12

If n = 4 and m = 1, then we have

-1 +2 -3 +4

Now your task is to find the summation of the numbers considering their signs.

Input

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case starts with a line containing two integers: n and m (2 ≤ n ≤ 109, 1 ≤ m). And you can assume that n is divisible by 2*m.

Output

For each case, print the case number and the summation.

Sample Input

2

12 3

4 1

Sample Output

Case 1: 18

Case 2: 2


分析:

简单题。(老是费劲做完才发现原来是到简单题。。。)

一看数据规模就知道从左往右算是必定要超时的。(可笑我还竟然试了一次,浪费了那么多时间。。。)

这种大规模数据我只想到几种情况:二分?动规?还是数学公式?

显然这题是数学公式。我们可以发现由n能被2m整除可得:所有数一定是先减m个再加m个。那么我们进一步发现:每次一减一加后,最后结果会多加m*m。比如-1,-2,-3,+4,+5,+6,可以看成(4-1)+(5-2)+(6-3)。而总共先减后加了n/2m次。所以最后结果就是m*m*n/2m=n*m/2。

这里还需观察一下数的范围:最坏情况下n=1000000000 m=500000000 ,所以最后答案需要long long。


#include <iostream>

using namespace std;

int main()
{
    int t;
    long long n,m;
    cin>>t;
    for (int i=0;i<t;i++)
    {
        cin>>n>>m;
        long long ans=n*m/2;
        cout<<"Case "<<i+1<<": "<<ans<<endl;
    }


    return 0;
}

你可能感兴趣的:(IO,input,each,64bit,Numbers)