本博客同步更新至: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;
}