E. Klee's SUPER DUPER LARGE Array!!!

Example

Input

4
2 2
7 2
5 3
1000000000 1000000000

Output

1
5
1
347369930

题目大意

[!TIP]

等差求和公式什么来着,本题求最小,和前面数组是一样的模板,难点在数学(确信)

使用二分查找来搜索 i,使得 rightleft 为绝对差值最小的数

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

int main() 
{
    int t;
    scanf("%d", &t);

    while (t--) {
        ll n, k;
        scanf("%lld %lld", &n, &k);

        ll res = 1e10;
        ll l = 1;
        ll r = n + 1;
        ll mid, right, left, baka;

        while (l < r) 
        {
            mid = l + (r - l) / 2;
            
            //右边的和 
            right = (n + k - 1) * (n + k) / 2 - (mid + k - 1) * (mid + k) / 2;
            //左边的和 
            left = (mid + k - 1) * (mid + k) / 2 - (k - 1) * k / 2;
            
            baka = right - left;
            res = min(res, abs(baka));//更新最小的绝对差值

            if (baka <= 0)
            {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        printf("%lld\n", res);
    }

    return 0;
}
posted @ 2024-11-14 14:33  土木牢盖  阅读(11)  评论(0编辑  收藏  举报