J. Wu Chengyao's common divisor (gcd & map.count() of multiple indices) (2021 Niuke Winter Holiday Algorithm Basic Training Camp 4)

Portal

Ideas:

When calculating the gcd of multiple numbers, it is nothing more than decomposing prime factors. For this problem, we need to decompose x_{i}^{p_{i}} the prime factors of n exponents  and find the common prime factor y and its smallest exponent w. The answer is all y ^ {w}products.

For example: GCD (24,32,36) = GCD ( 2^{3} * 3 2^{4}, 2^{2} * 3^{2}), a common prime factors 2, 3, respectively, appeared, 4, 2, 2 on the minimum number of occurrences, so gcd (24, 32, 36) 2^{2} == 4.

Code:

#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;
}

 

Guess you like

Origin blog.csdn.net/Satur9/article/details/114489583