【Codeforces 632D】 Longest Subsequence

【题目链接】

           点击打开链接

【算法】

      设取的所有数都是k的约数,则这些数的lcm必然不大于k。

      对于[1, m]中的每个数,统计a中有多少个数是它的约数即可。

【代码】

         

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MAXN = 1e6;

ll i,j,tmp,num,maxx,n,m,res;
ll a[MAXN+10],sum[MAXN+10],h[MAXN+10];
vector<ll> ans;

template <typename T> inline void read(T &x) {
        ll f = 1; x = 0;
        char c = getchar();
        for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
        for (; isdigit(c); c = getchar()) x = x * 10 + c - '0';
        x *= f;
}

template <typename T> inline void write(T x) {
    if (x < 0) { putchar('-'); x = -x; }
    if (x > 9) write(x/10);
    putchar(x%10+'0');
}

template <typename T> inline void writeln(T x) {
    write(x);
    puts("");
}

inline ll gcd(ll x,ll y) { return y == 0 ? x : gcd(y,x%y); }

int main() {
        
        read(n); read(m);
        for (i = 1; i <= n; i++) {
                read(a[i]);
                if (a[i] <= m)
                        ++h[a[i]];
        }
        for (i = 1; i <= m; i++) {
                tmp = i;
                if (!h[i]) continue;
                for (j = tmp; j <= m; j += tmp) {
                        sum[j] += h[i];
                }    
        }
        for (i = 1; i <= m; i++) {
                if (sum[i] > maxx) {
                        maxx = sum[i];
                        num = i;
                }    
        } 
        
        if (!num) {
                printf("1 0
");
                return 0;
        }
        
        for (i = 1; i <= n; i++) {
                if (!(num % a[i]))
                    ans.push_back(i);        
        }
        
        res = a[ans[0]];
        for (i = 1; i < ans.size(); i++) res = res * a[ans[i]] / gcd(res,a[ans[i]]);
        write(res); putchar(' '); write(ans.size()); puts("");
        for (i = 0; i < ans.size(); i++) {
                write(ans[i]);
                if (i < ans.size() - 1) putchar(' ');    
        }
        
        return 0;
    
}
原文地址:https://www.cnblogs.com/evenbao/p/9196405.html