Codeforces Round #552 (Div. 3)G Minimum Possible LCM (数论+优化枚举状态)

题目链接:http://codeforces.com/contest/1154

题目大意

给定一序列数,问其中两个数的lcm

最小值是多少.

题目分析 

这道题大致就是我最近一直想着的优化决策问题,或者说是

优化枚举状态问题,所有答案候选集合明显过大了,要想办法优化,

我们可以把每个数都丢到其所有因子的桶中试试看,

如果对于同一个因子,有若干个数根据贪心的思想我们只要把

前两个产生的权值纳入答案的比较即可.

但对每个数因数分解复杂度不允许.....

所以再采用另一种做法,就是对于每个i枚举i的倍数,

当碰到第二个符合要求的数时候直接产生权值比较然后break掉.

对于相同的两数直接在输入的时候就可以判定出来纳入候选了.

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

#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long

#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))
#define pii pair<int,int>
#define fi first
#define se second
#define mk(x,y) make_pair(x,y)
const int mod=1e9+7;
const int maxn=1e7+100;
const int ub=1e6;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
int gcd(int x,int y){
    if(y==0) return x;
    return gcd(y,x%y);
}
/*
题目大意:
给定一序列数,问其中两个数的lcm
最小值是多少.

题目分析:
这道题大致就是我最近一直想着的优化决策问题,或者说是
优化枚举状态问题,所有答案候选集合明显过大了,要想办法优化,
我们可以把每个数都丢到其所有因子的桶中试试看,
如果对于同一个因子,有若干个数根据贪心的思想我们只要把
前两个产生的权值纳入答案的比较即可.
但对每个数因数分解复杂度不允许.....
所以再采用另一种做法,就是对于每个i枚举i的倍数,
当碰到第二个符合要求的数时候直接产生权值比较然后break掉.
对于相同的两数直接在输入的时候就可以判定出来纳入候选了.
*/
int n;
vector<int> cnt[maxn];
ll LCM(int x,int y){
    return 1LL*x/gcd(x,y)*y;
}
int main(){
    ios::sync_with_stdio(false);
    cin>>n;
    ll ans=1e18;
    int retl,retr,l,r,vl,vr;
    rep(i,0,n){
        int x;cin>>x;
        if(cnt[x].size()){
            if(x<ans){
                ans=x;
                retl=i+1,retr=cnt[x][0];
            }
        }
        else cnt[x].push_back(i+1);
    }
    rep(i,1,maxn){
        l=-1,r=-1;
        for(int j=i;j<maxn;j+=i){
            if(cnt[j].size()==0) continue;
            if(l==-1){
                l=j;vl=cnt[j][0];
            }else{
                r=j;vr=cnt[j][0];
                ///cout<<l<<" "<<r<<endl;
                ll tmp=LCM(l,r);
                if(tmp<ans){
                    ans=tmp;
                    retl=vl,retr=vr;
                }
                break;
            }
        }
    }
    if(retl>retr) swap(retl,retr);
    cout<<retl<<" "<<retr;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37451344/article/details/89741220
今日推荐