链接

题目描述: 有a个红色棋子,b个蓝色棋子放在n*n的棋盘上,要求同色的上下左右不能相邻,找出最小的n,棋盘可以有多余位置。

题解:看到的 第一眼还以为要染色,比划了几下发现和数学相关,本题的关键点就是找到在n * n棋盘上被分为两部分的点的个数,较少的个数为 mi = n * n / 2 下取整 则较多的个数为 ma = n * n - n * n/2 。有了这个公式就好办了。找n的时候我采用了二分的方法,因为题目中a的范围是1e9,开根号约1e5。所以定义l为1 , r为1e5。进行二分查找。check的条件是(ma>=max(a,b) && mi>=min(a,b))只有同时大于等于才能收缩,否则会影响答案。

代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
#include <math.h>
#include <string>
#define PI 3.14159
using namespace std;

typedef pair<int,int> PII;
typedef long long LL;
const int MAX_INT =  0x3f3f3f3f;
const int N = 1e5+15;
const int mod = 1e9+7;

void solve()
{
    int a,b;
    cin>>a>>b;
    int res = 0;
    int l = 1;
    int r = N;
    while(l<r)
    {
        LL mid = (l+r)/2;
        LL mi = mid*mid/2;
        LL ma = mid * mid - mi ;
        
        if(ma>=max(a,b) && mi >= min(a,b))r=mid;
        else l = mid+1;
    }
    cout<<l<<endl;
}

int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    
    int T = 1;
    cin>>T;
    while(T--)
    {
        solve();
    }
}

还有一种极其简单的解题方式

int main()
{
    int T;
    cin >> T;
    while(T--)
    {
        int a,b;
        cin >> a >> b;
        if(a!= b)//不等的话 找出最大值*2-1 开根号
        {
            cout << ceil(sqrt(2*max(a,b)-1)) << endl;
        }
        else cout << ceil(sqrt(2*a)) << endl;
         
    }
}