J. Wu Chengyaoの最大公約数(複数のインデックスのgcd&map.count())(2021 Niuke Winter Holiday Algorithm Basic Training Camp 4)

ポータル

アイデア:

複数の数のgcdを計算する場合、素因数を分解するだけです。この問題ではx_ {i} ^ {p_ {i}} 、n個の指数の素因数を分解し、共通の素因数yとその最小の指数wを見つける必要が あります。答えはすべてのy ^ {w}積です。

例:GCD(24,32,36)= GCD(2 ^ {3} * 3 2 ^ {4}2 ^ {2} * 3 ^ {2})、それぞれ共通の素因数2、3が出現し、最小発生数で4、2、2なので、gcd(24、32 、 36)2 ^ {2} == 4。

コード:

#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {
   
   {1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int  inf = 0x3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-6;
const ll   mod = 1e9+7;
const int  N = 2e5 + 5;

inline void read(int &x){
    char t=getchar();
    while(!isdigit(t)) t=getchar();
    for(x=t^48,t=getchar();isdigit(t);t=getchar()) x=x*10+(t^48);
}


int qmi(int a, int k)
{
    int res = 1;
    while(k){
        if(k & 1) res = (ll)res * a % mod;
        k >>= 1;
        a = (ll)a * a % mod;
    }
    return res;
}

int n, x[N], p[N];
vector<int> v;
unordered_map<int, int> mp, ct;

signed main()
{
    IOS;
    cin >> n;
    for(int i = 0; i < n; i ++) cin >> x[i];
    for (int i = 0; i < n; i++) cin >> p[i];
    for(int i = 0; i < n; i ++){
        int pre = x[i];
        for(int j = 2; j <= pre/j; j ++){ //进行质因数分解
            if(pre%j==0){
                mp[j] ++; //统计质因数j出现的次数
                int cnt = 0;
                while(pre%j==0){
                    pre /= j;
                    cnt ++;
                }
                cnt *= p[i];
                if(!ct.count(j)) ct[j] = cnt; //更新质因数j在每个数中出现的最小次数
                else ct[j] = min(ct[j], cnt);
            }
        }
        if(pre>1){
            mp[pre] ++;
            if(!ct.count(pre)) ct[pre] = p[i];
            else ct[pre] = min(ct[pre], p[i]);
        }
    }
    for(auto &u:mp)
        if(u.second==n)  //如果这个质因数出现了n次
            v.push_back(u.first);
    int ans = 1;
    for(auto &u:v) ans = ans*qmi(u, ct[u])%mod; //答案就是所有出现n次质因数与其最小次数的乘积
    cout << ans << endl;

    return 0;
}

 

おすすめ

転載: blog.csdn.net/Satur9/article/details/114489583