2018icpc南京 Problem J. Prime Game

it2026-08-07  5

题意 计算出来每个数的质因子在各个区间的贡献 Input The first line contains one integer n (1 ≤ n ≤ 106) — the length of the sequence. The second line contains n integers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 106) — the sequence. Output Print the answer to the equation. Examples standard input 10 99 62 10 47 53 9 83 33 15 24 standard output 248 standard input 10 6 7 5 5 4 9 9 1 8 12 standard output 134

思路 素数筛 + 一个pre数组表示之前的位置 训练时看懂了题目想到了素数筛(这是必然要用的),后来看到数三角形就去做数三角形了,再后来经人点拨pre数组,想到了这个做法。

#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e6+5; inline void input(int& res) { char c = getchar();res = 0;int f = 1; while (!isdigit(c)) { f ^= c == '-'; c = getchar(); } while (isdigit(c)) { res = (res << 3) + (res << 1) + (c ^ 48);c = getchar(); } res = f ? res : -res; } int prime[N+5],vis[N+5],a[N+5],pre[N+5]; int Case,n,cnt; ll ans,l,r; void Euler() { for(int i=2;i<=N;i++) { if(vis[i]==0) prime[++cnt]=i; for(int j=1;j<=cnt&&i*prime[j]<=N;j++) { vis[i*prime[j]]=1; if(i%prime[j]==0) break; } } } int main(){ Euler(); input(n); for(int i=1;i<=n;i++) input(a[i]); for(int i=1;i<=n;i++){ for(int j=1;j<=cnt&&a[i]>=prime[j]*prime[j];j++){ if(a[i]%prime[j]==0){ l=i-pre[prime[j]]; r=n-i+1; ans+=l*r; pre[prime[j]]=i; while(a[i]%prime[j]==0){ a[i]/=prime[j]; } } } if(a[i]!=1){ l=i-pre[a[i]]; r=n-i+1; ans+=l*r; pre[a[i]]=i; } } printf("%lld\n",ans); return 0; }
最新回复(0)