Codeforces Round #552 (Div. 3) G C++

题目:

  

G. Minimum Possible LCM
time limit per test
4 seconds
memory limit per test
1024 megabytes
input
standard input
output
standard output

You are given an array aa consisting of nn integers a1,a2,,ana1,a2,…,an.

Your problem is to find such pair of indices i,ji,j (1i<jn1≤i<j≤n) that lcm(ai,aj)lcm(ai,aj) is minimum possible.

lcm(x,y)lcm(x,y) is the least common multiple of xx and yy (minimum positive number such that both xx and yy are divisors of this number).

Input

The first line of the input contains one integer nn (2n1062≤n≤106) — the number of elements in aa.

The second line of the input contains nn integers a1,a2,,ana1,a2,…,an (1ai1071≤ai≤107), where aiai is the ii-th element of aa.

Output

Print two integers ii and jj (1i<jn1≤i<j≤n) such that the value of lcm(ai,aj)lcm(ai,aj) is minimum among all valid pairs i,ji,j. If there are multiple answers, you can print any.

  题目就是让找出两个数,是这两个数的最小公倍数最小,输出这两个数的下标。

TLE代码

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int gcd(int x,int y)
{
    if(!y) return x;
    else return gcd(y,x%y);
}
int a[1000010];
int main ()
{
   int n,t,x,y;
   long long sum=9e18;
   cin>>n;
   for(int i=1;i<=n;i++)
    cin>>a[i];
    for(int i=1;i<=n-1;i++)
    for(int j=i+1;j<=n;j++){
        if(a[i]>a[j]) t=gcd(a[i],a[j]);
        else t=gcd(a[j],a[i]);
        long long int h=a[i]/t*a[j];
        if(h<sum) sum=h,x=i,y=j;
    }
    cout<<x<<' '<<y<<endl;
   return 0;
}

  本蒟蒻的代码,求出任意两个数的最小公倍数,还是TLE了(ssfd)

借鉴大佬的代码(AC):

#include<bits/stdc++.h>
using namespace std;
const int maxn=10000000+5;
long long int ans=0x3f3f3f3f3f3f3f3f;
int a[maxn],b[maxn];
int main ()
{
    int n,i,j,ansj,ansi,x;
    cin>>n;
    for(i=1;i<=n;i++){
        scanf("%d",&a[i]);
        if(b[a[i]]&&ans>a[i]) ans=a[i],ansi=i,ansj=b[a[i]];
        b[a[i]]=i;
    }
    for(i=1;i<maxn;i++)
    for(x=0,j=i;j<maxn;j+=i){
        if(b[j]){
            if(x==0) x=j;
            else{
                if(ans>1LL*x*j/i) ans=1LL*x*j/i,ansj=b[j],ansi=b[x];
            }
        }
    }
    if(ansi>ansj) swap(ansi,ansj);
    cout<<ansi<<' '<<ansj;
   return 0;
}

猜你喜欢

转载自www.cnblogs.com/-xyp/p/10743008.html