Educational Codeforces Round 78 (Rated for Div. 2) B. A and B

链接:

https://codeforces.com/contest/1278/problem/B

题意:

You are given two integers a and b. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by 1; during the second operation you choose one of these numbers and increase it by 2, and so on. You choose the number of these operations yourself.

For example, if a=1 and b=3, you can perform the following sequence of three operations:

add 1 to a, then a=2 and b=3;
add 2 to b, then a=2 and b=5;
add 3 to a, then a=5 and b=5.
Calculate the minimum number of operations required to make a and b equal

思路:

先转换成,前n个数,分成两堆,差为a和b的差,
打一个前缀和,猜了一下,分成的两堆差肯定为a和b的差,考虑不断给两边加上1,如果总和是前n项和,答案就是n。
卡了一个小时。。

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;

LL sum[1000010];

int main()
{
    int t;
    cin >> t;
    sum[0] = 0, sum[1] = 1;
    for (int i = 1;i <= 1000000;i++)
        sum[i] = sum[i-1]+i;
    while(t--)
    {
        int a, b;
        cin >> a >> b;
        if (a == b)
        {
            cout << 0 << endl;
            continue;
        }
        int sub = abs(a-b);
        int res = 0;
        for (int i = 1;i <= 1000000;i++)
        {
            if (sum[i] < sub)
                continue;
            if ((sum[i]-sub)%2 == 0)
            {
                res = i;
                break;
            }
        }
        cout << res << endl;
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/YDDDD/p/12076349.html