算法总结——二分GCD

· · 算法·理论

例题1 最大公约数

细节:

思路:

首先要明确,多个数 \gcd 的结果与计算顺序无关,即 \gcd(a,b,c,d)=\gcd(a,\gcd(b,\gcd(c,d)))=\gcd(\gcd(a,b),\gcd(c,d))。

于是题目转换成:按照曼哈顿距离一层一层的取 \gcd,至少要取多少层 \gcd 为 1。

代码:

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

struct node {int x,y,steps;};
long long n,m,a[2005][2005],pre[2005][2005],ans = 0,stx,sty;
bool vis[2005][2005];
const long long dx[4] = {0,0,-1,1};
const long long dy[4] = {-1,1,0,0};
queue<node>q;

long long gcd(long long a,long long b)
{
    if(b == 0) return a;
    return gcd(b,a%b);
}

bool check(void)
{
    long long g = a[1][1];
    for(int i = 1;i <= n;i++)
    {
        for(int j = 1;j <= m;j++) g = gcd(g,a[i][j]);
    }
    return g == 1;
}

int bfs()
{
    q.push({stx,sty,0});
    vis[stx][sty] = 1;
    if(a[stx][sty] == 1) return 0;
    while(q.size())
    {
        node u = q.front();
        q.pop();
        for(int i = 0;i < 4;i++)
        {
            int nx = u.x+dx[i],ny = u.y+dy[i];
            if(nx < 1 || ny < 1 || nx > n || ny > m) continue;
            if(vis[nx][ny]) continue;
            vis[nx][ny] = 1;
            a[u.x][u.y] = gcd(a[u.x][u.y],a[nx][ny]);
            if(a[u.x][u.y] == 1) return u.steps+1;
            q.push({nx,ny,u.steps+1});
        }
    }
    return -1;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for(int i = 1;i <= n;i++)
    {
        for(int j = 1;j <= m;j++) cin >> a[i][j];
    }
    cin >> stx >> sty;
    if(check() == 0)
    {
        cout << -1;
        return 0;
    }
    cout << bfs();
    return 0;
}

例题2 指导

思路:

先计算出处理完前 m-1 个同学的问题需要的最少时间,再找到编号最小的,正好处理完最后一个同学的老师。

那么,怎么计算出处理完前 m-1 个同学的问题需要的最少时间呢?如果给老师们 x 的时间能处理完,那么给 x+1 的时间肯定也能完成,单调性成立,可以用二分答案。已知时间,可以直接计算出老师可以处理的学生数量,检查 n 个老师总共可以处理的学生数量是否大于等于 m。

代码:

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

struct node 
{
    int x,id;
    bool operator<(const node &b)const
    {
        if(x != b.x) return x > b.x;
        return id > b.id;
    }
};
long long n,m,a[100005],ans = 0;

bool check(long long x)
{
    long long cnt = 0;
    for(int i = 1;i <= n;i++) cnt += (x-1+a[i])/a[i];
    return cnt >= m;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for(int i = 1;i <= n;i++) cin >> a[i];
    if(m <= n)
    {
        cout << m;
        return 0;
    }
    long long l = 0,r = m*1e7+1;
    while(l+1 < r)
    {
        long long mid = (l+r)/2;
        if(check(mid)) r = mid;
        else l = mid;
    }
    l++;
    long long last = 0;
    for(int i = 1;i <= n;i++) last += (l-2+a[i])/a[i];
    for(int i = 1;i <= n;i++)
    {
        if((l-1)%a[i] == 0)
        {
            last++;
            if(last == m)
            {
                cout << i;
                return 0;
            }
        }
    }
    return 0;
}