[CF1493D] GCD of an Array - 数论,map,set
Description
一个长度为 (n) 的序列 (a)。(m) 次操作,每次操作你要将 (a_x) 乘 (y),然后输出 (gcd(a_1,cdots,a_n)mod (10^9+7))。(1le n,mle 2 imes 10^5),(1le a_i,yle 2 imes 10^5),(1le xle n)。
Solution
对每个数用 map 维护其质因子出现次数,对每个质因子用 multiset 维护其在所有数中的出现次数
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 200005;
const int mod = 1e9 + 7;
map<int, int> a[N];
multiset<int> s[N];
int qpow(int p, int q)
{
return (q & 1 ? p : 1) * (q ? qpow(p * p % mod, q / 2) : 1) % mod;
}
int inv(int p)
{
return qpow(p, mod - 2);
}
vector<pair<int, int>> Factorial(int n)
{
vector<pair<int, int>> ans;
for (int i = 2; i * i <= n; i++)
{
if (n % i == 0)
{
int cnt = 0;
while (n % i == 0)
n /= i, ++cnt;
ans.push_back({i, cnt});
}
}
if (n > 1)
ans.push_back({n, 1});
return ans;
}
signed main()
{
ios::sync_with_stdio(false);
int n, q;
cin >> n >> q;
int ans = 1;
for (int i = 1; i <= n; i++)
{
int x;
cin >> x;
vector<pair<int, int>> fac = Factorial(x);
for (auto [x, y] : fac)
{
a[i][x] += y;
s[x].insert(y);
}
}
for (int i = 1; i < N; i++)
{
if (s[i].size() == n)
{
int q = *s[i].begin();
ans = (ans * qpow(i, q)) % mod;
}
}
for (int i = 1; i <= q; i++)
{
int pos, val;
cin >> pos >> val;
vector<pair<int, int>> fac = Factorial(val);
for (auto [x, y] : fac)
{
int old = a[pos][x];
if (old && s[x].size() == n)
ans = (ans * inv(qpow(x, *s[x].begin()))) % mod;
if (old)
s[x].erase(s[x].find(old));
int tmp = a[pos][x] += y;
s[x].insert(tmp);
if (tmp && s[x].size() == n)
ans = (ans * (qpow(x, *s[x].begin()))) % mod;
}
cout << ans << endl;
}
}