Codeforces Round #552 (Div. 3) G. Minimum Possible LCM(埃氏筛法枚举GCD)

G. Minimum Possible LCM

题意:求 n n 个数中最小公倍数数值最小的两个数的下标。

题解:参考于https://blog.csdn.net/qq_41157137/article/details/89353527,因为 L C M ( x , y ) = x × y g c d ( x , y ) LCM(x,y) = \frac{x\times y}{gcd(x,y)}
对于包含 d = g c d ( x , y ) d = gcd(x,y) 的数 x 1 , x 2 , x 3 . . . x i ( x 1 < x 2 < x 3 . . . x i ) x_1,x_2,x_3...x_i(x_1 <x_2<x_3...x_i)
如果 d d x 1 , x 2 x_1,x_2 的最大公因数,那么 l c m ( x 1 , x 2 ) lcm(x_1,x_2) 一定小于 x 1 × x 3 d \frac{x_1\times x_3}{d} ,剩下亦是如此;
如果 d d 不是 x 1 , x 2 x_1,x_2 的最大公因数,那么 l c m ( x 1 , x 2 ) lcm(x_1,x_2) 也一定小于 x 1 × x 2 d \frac{x_1\times x_2}{d} ,如果 d d x 1 , x 4 x_1,x_4 的最大公因数,同样满足 l c m ( x 1 , x 2 ) < x 1 × x 4 d lcm(x_1,x_2)<\frac{x_1\times x_4}{d}

所以综上所述,只需要枚举最大公因数 d d ,然后取包含前两项的 a i a_i 并且最后取 m i n min 即可。

代码

#include<bits/stdc++.h>

#define DEBUG(x) std::cerr << #x << '=' << (x) << std::endl
typedef long long LL;
using namespace std;
constexpr int N = 1E7+10;
int pos[N];

int main()
{
#ifndef ONLINE_JUDGE
    freopen("input.in","r",stdin);
#endif
    ios::sync_with_stdio(false); cin.tie(nullptr);
    int n, v, xi = 0, yi = 0;
    cin >> n;
    LL ret = LLONG_MAX;
    for(int i = 1; i <= n; ++i) {
        cin >> v;
        if(pos[v] && v < ret) {
            ret = v; //相同的数lcm肯定就是本身啦
            xi = pos[v];
            yi = i;
        }
        pos[v] = i;
    }
    for(int d = 1; d < N; ++d) {
        for(int x = 0, y = d; y < N; y += d) {
            if (pos[y]) { //因子包含d的数
                if (x == 0) { x = y; }
                else if (ret > 1LL * x * y / d) ret = 1LL * x * y / d, xi = pos[x], yi = pos[y];
            }
        }
    }
    if(xi > yi) swap(xi, yi);
    cout << xi << ' ' << yi << endl;
    return 0;
}

发布了219 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/Eternally831143/article/details/89367754
今日推荐