题解:P17327 [ICPC 2018 Nanjing R] Prime Game
A7F3jK9pR0xf_ · · 题解
题目传送门
首先不难发现
于是考虑拆贡献。具体地,我们考虑每个质因数对答案产生了多少贡献。由于每个数值域为
我们考虑对于每个质因数,怎么样去计算它们的答案。假设我们现在在考虑某个质因数,在数组上有一些数具有这个质因数,我们视有质因数的点是被点亮的。那么这个质因数产生贡献实际上就是计算有多少个
综上,总复杂度为
#include <bits/stdc++.h>
using namespace std;
#define il inline
#define pb emplace_back
typedef long long ll;
const int N = 1e6 + 10;
int pri[N / 10], tot, minp[N];
bool vis[N];
il void euler(int n)
{
vis[0] = vis[1] = 1;
for(int i = 2;i <= n;++i)
{
if(!vis[i]) pri[++tot] = i, minp[i] = i;
for(int j = 1;pri[j] <= n / i;++j)
{
vis[i * pri[j]] = 1;
minp[i * pri[j]] = pri[j];
if(i % pri[j] == 0) break;
}
}
}
unordered_map<int, vector<int> > mp;
il ll c2(int n)
{
if(n <= 0) return 0;
return 1ll * n * (n + 1) / 2;
}
int main()
{
int n;
cin >> n;
euler(1e6);
for(int i = 1;i <= n;++i)
{
int x;
cin >> x;
while(x > 1)
{
int y = minp[x];
mp[y].pb(i);
while(x % y == 0) x /= y;
}
}
ll ans = 0;
for(auto i : mp)
{
vector<int> tmp = i.second;
tmp.pb(n + 1);
tmp.insert(tmp.begin(), 0);
ans += c2(n);
for(int j = 0;j < tmp.size() - 1;++j) ans -= c2(tmp[j + 1] - tmp[j] - 1);
}
cout << ans;
return 0;
}