本博客同步更新至:https://startcraft.cn
题目链接:https://codeforces.com/gym/101981/attachments
Given a suqence of n integers \(a_{i}\)
Let \(mul(l, r)\) = \(\prod ^{r}_{i=1}\)and\(fac(l,r)\)be the number of distinct prime factors of\(mul(l,r)\).
Please calculate \(\sum ^{n}_{i=1}\sum ^{n}_{j=1}fac(i,j)\)
Input
The first line contains one integer \(n (1\leq n\leq 10^{6})\)— the length of the sequence.
The second line contains n integers \(a_{i} (1\leq a_{i}\leq 10^{6})\)—the sequence.
Output
Print the answer to the equation.
Examples
in:
10
99 62 10 47 53 9 83 33 15 24
out:
248
in:
10
6 7 5 5 4 9 9 1 8 12
out:
134
思路:计算每个质因子的贡献,首先从ai开始,分解质因数,记录每个质因数P出现的的位置,每个质数P的贡献是
\(n-i+(n-i)*(i-pos[P]-1)\)其中pos[p]是上一次质数出现的位置,i从0开始,n是总数,若P是第一次出现则贡献是\(n-i+i(n-i)\)
n-i代表的就是这个质数对后面的所有数都有贡献,然后\((n-i)*(i-pos[P]-1)\)代表的是这个质数从当前位置到pos[P]是新出现的,所以前面没有计算它要加上它。
当时在赛场上,死活没调对,还是太菜了
AC代码:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
typedef long long ll;
#define wfor(i,j,k) for(i=j;i<k;++i)
#define mfor(i,j,k) for(i=j;i>=k;--i)
// void read(int &x) {
// char ch = getchar(); x = 0;
// for (; ch < '0' || ch > '9'; ch = getchar());
// for (; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
// }
const int maxn=1e6+5;
int num[maxn];
int prime[maxn];
void get_prime()
{
int i;
wfor(i,2,maxn)
{
if(!prime[i])
prime[++prime[0]]=i;
int j;
for(j=1;j<=prime[0]&&prime[j]*i<maxn;j++)
{
prime[prime[j]*i]=1;
if(i%prime[j]==0)
break;
}
}
}
int pos[maxn];
int main()
{
std::ios::sync_with_stdio(false);
#ifdef test
freopen("F:\\Desktop\\question\\in.txt","r",stdin);
#endif
#ifdef ubuntu
freopen("/home/time/debug/debug/in","r",stdin);
freopen("/home/time/debug/debug/out","w",stdout);
#endif
int n;
cin>>n;
int i;
get_prime();
ll ans=0;
wfor(i,0,n)
{
cin>>num[i];
}
memset(pos,-1,sizeof(pos));
wfor(i,0,n)
{
int temp=num[i];
int j;
for(j=1;j<=prime[0]&&prime[j]*prime[j]<=temp;j++)//分解质因数
{
if(temp%prime[j]==0)
{
if(pos[prime[j]]==-1)//这个质数第一次出现
ans+=(n-i)+(n-i)*i;
else
{
ans+=n-i;
ans+=(n-i)*(i-pos[prime[j]]-1);
}
pos[prime[j]]=i;//记录该质数出现的位置
while(temp%prime[j]==0)
temp/=prime[j];
}
}
if(temp>1)
{
if(pos[temp]==-1)
ans+=(n-i)+(n-i)*i;
else
{
ans+=n-i;
ans+=(n-i)*(i-pos[temp]-1);
}
pos[temp]=i;
}
}
cout<<ans<<endl;
return 0;
}