7 8号点tle了,大佬救命!

P1029 [NOIP2001 普及组] 最大公约数和最小公倍数问题

Eryi117 @ 2024-07-25 11:50:41

#include<iostream>
#include<map>
#include<vector>
#include<deque>
#include<algorithm>
#include<unordered_map>
#include<set>
#include<string>
using namespace std;
#define ios ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define mm(a, b) memset(a, b, sizeof(a))
#define ll long long
#define mp make_pair
typedef unsigned long long ull;
typedef pair<int, int> pii;
const int inf = 0x3f3f3f3f;
const int N = 1e6 + 10;

ll n;

ll gcd(ll a, ll b){
    return b ? gcd(b, a % b) : a;
}

ll lcm(ll a, ll b) {
    return a / gcd(a, b) * b;
}

void solve() {
    ll x, y;
    cin >> x >> y;
    if (x == y) {
        cout << 1;
        return;
    }
    ll ans = 0;
    for (ll i = x; i <= y; i += x)
        for (ll j = i; j <= y; j += x)
            if (lcm(i, j) == y && gcd(i, j) == x) ans += 2;

    cout << ans;
}

int main() {
    ios;
    int t;
    //cin >> t;
    t = 1;
    while (t--) solve();
    return 0;
}

by haimingbei @ 2024-07-25 12:08:18

@Eryi117

代码如下(AC,求关)

先找出满足x0是因数和y0是倍数的两个数,然后在判断是不是最小公因数(最小公约数)和最小公倍数

#include<bits/stdc++.h>
using namespace std;
int main(){
    int x0,y0,ans=0;
    cin>>x0>>y0;
    int n=x0*y0;
    for(int i=x0;i<=y0;i++){
        if(n%i==0){
            int a=n/i;
            bool f=1;
            if(a%x0==0 && i%x0==0 && y0%a==0 && y0%i==0){
                int x=min(i,a),y=max(i,a);
                for(int j=x0+1;j<=x;j++)
                    if(i%j==0 && a%j==0)f=0;
                for(int k=y;k<y0;k++)
                    if(k%i==0 && k%a==0)f=0;
                if(f==1)ans++;
            }   
        }
    }
    cout<<ans;
    return 0;
}

by haimingbei @ 2024-07-25 12:09:53

时间复杂度是O(n^2),你的是O(n^3)


by Eryi117 @ 2024-07-26 08:46:18

@haimingbei 我的代码时间复杂度应该介于O((y/x)^2)到O(n^2),我main函数里的while循环可以去掉的。


|