P6583 Solution
NaCly_Fish · · 题解
感觉今天被这题打成 SB 了,,写篇题解纪念一下。
首先不难想到,对于最简分数
那么枚举
发现
把后一个和式中的
由于只有
(除法向下取整)
由此就能得到 80 分代码
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#define ll long long
#define reg register
using namespace std;
ll n,ans;
inline ll solve(ll a,ll b){
ll res = 0,lim = n/(a*b),tmp,d;
for(reg ll l=1,r;l<=lim;l=r+1){
d = n/l;
tmp = d,r = n/d;
if(a>1) tmp -= d/2;
if(b>1) tmp -= d/5;
if(a>1&&b>1) tmp += d/10;
res += tmp*(r-l+1);
}
return res;
}
int main(){
scanf("%lld",&n);
for(reg ll a=1;a<=n;a<<=1)
for(reg ll b=1;a*b<=n;b*=5)
ans += solve(a,b);
printf("%lld",ans);
return 0;
}
优化成满分做法其实很简单,,,注意到和式中虽然上界在变,但其中
所以就把除法分块中每一段预处理好,做个前缀和,这样对每一组
时间复杂度应该是
满分做法(可以不用编译优化):
#pragma GCC optimize (2)
#pragma GCC optimize ("unroll-loops")
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define N 1000003
#define ll long long
#define reg register
using namespace std;
struct node{
ll s1,s2,s5,s10;
}pre[N<<1];
ll R[N<<1];
int cnt;
inline void prepare(ll n){
ll d;
for(reg ll l=1,r;l<=n;l=r+1){
d = n/l,++cnt;
R[cnt] = r = n/d;
pre[cnt].s1 = d*(r-l+1),pre[cnt].s2 = (d/2)*(r-l+1);
pre[cnt].s5 = (d/5)*(r-l+1),pre[cnt].s10 = (d/10)*(r-l+1);
}
for(reg int i=2;i<=cnt;++i){
pre[i].s1 += pre[i-1].s1,pre[i].s2 += pre[i-1].s2;
pre[i].s5 += pre[i-1].s5,pre[i].s10 += pre[i-1].s10;
}
R[cnt+1] = 1ll<<60;
}
ll n,ans;
inline ll solve(ll a,ll b){
ll r,d,res = 0,lim = n/(a*b);
int pos = upper_bound(R+1,R+cnt+2,lim)-R-1;
r = R[pos],d = n/(r+1);
res = pre[pos].s1+d*(lim-r);
if(a>1) res -= pre[pos].s2+(d/2)*(lim-r);
if(b>1) res -= pre[pos].s5+(d/5)*(lim-r);
if(a>1&&b>1) res += pre[pos].s10+(d/10)*(lim-r);
return res;
}
int main(){
scanf("%lld",&n);
prepare(n);
for(reg ll a=1;a<=n;a<<=1)
for(reg ll b=1;a*b<=n;b*=5)
ans += solve(a,b);
printf("%lld",ans);
return 0;
}