Codeforces Round #828 (Div. 3) E2 // 数论 + dfs

题目来源:Codeforces Round #828 (Div. 3) E2 - Divisible Numbers

题目链接:Problem - E2 - Codeforces


题意

t 组案例(1 t10),对于每个案例:给定四个整数a,b,c,d1a<c109,1b<d109),求一组整数x,y,满足a<xcb<ydab | xy,若不存在,则输出1 1

思路:数论 + dfs

ab | xy 可知,存在整数res1,res2满足:res1·res2=ab,res1 | x,res2 | y,即 res1,res2ab 的因数,xres1 的倍数,yres2 的倍数。

于是有如下做法:

  1. 先对 ab 分解质因数
  2. 再dfs枚举 ab 的第一个因数 res1,则 res2=abres1
  3. 由于a<xcb<yd,于是先找出大于 a 的最小的 res1 的倍数,以及大于 b 的最小的 res2 的倍数,即令x=a+1res1·res1=a+1+res11res1·res1y=b+1res2·res2=b+1+res21res2·res2,若求出的值满足:xcyd,则说明成功找出一组解。

ab 的因数个数为 ω,由于 [1,1018] 范围内的数的因数个数最多为103680,因此有 ω103680
时间复杂度:O(t·(a+b+ω)).

代码

#include <bits/stdc++.h>
#define endl '\n'
#define LL long long
#define PII pair<int,int>
using namespace std;

int a, b, c, d;
map<int, int> mp;
vector<PII> v;
bool ok;

void getPrimes(int x)
{
    for(int i = 2; i <= x / i; ++ i) {
        while(x % i == 0) ++ mp[i], x /= i;
    }
    if(x > 1) ++ mp[x];
}

void dfs(int u, LL res)
{
    if(ok) return;
    if(u == v.size()) {
        LL res2 = (LL)a * b / res;
        LL x = (a + 1 + res - 1) / res * res, y = (b + 1 + res2 - 1) / res2 * res2;
        if(x <= c && y <= d) {
            cout << x << " " << y << endl;
            ok = true;
        }
        return;
    }
    LL mul = 1;
    for(int i = 0; i <= v[u].second; ++ i) {
        dfs(u + 1, res * mul);
        mul *= v[u].first;
    }
}

void solve()
{
    cin >> a >> b >> c >> d;

    mp.clear();
    getPrimes(a), getPrimes(b);

    v.clear();
    for(auto p : mp) v.push_back(p);

    ok = false;
    dfs(0, 1);
    if(!ok) cout << -1 << " " << -1 << endl;
}

int main()
{
    cin.tie(0);
    ios::sync_with_stdio(false);

    int test;
    cin >> test;
    while(test--) solve();

    return 0;
}
posted @   Jakon  阅读(53)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示