【题解】HDU 5970 最大公约数

solution:
网上一堆错解。
考虑 gcd 的性质: g(i+kj,j)=g(i,j)
观察到 m<=666 ,考虑枚举 (i,j) 其中 i<=j 。
记 c(i,j) 表示迭代的次数。不难发现 c(i,j) <=log(j)+1 ,这里有一个下取整很烦,记 g=gcd(i,j) ,枚举 k\in [0,c) ,观察到 ⌊ ( i + c j ) ∗ j / g 2 c ) ⌋ = ⌊ ( i ∗ j / g 2 c ) + ( c ∗ j 2 ) / ( g 2 ∗ c ) ⌋ = ⌊ ( i ∗ j / g 2 c ) ⌋ + ( j / g ) 2 \lfloor (i+cj)*j/g^2c) \rfloor=\lfloor (i*j/g^2c)+(c*j^2)/(g^2*c) \rfloor=\lfloor (i*j/g^2c) \rfloor+(j/g)^2 (i+cj)j/g2c)=(ij/g2c)+(cj2)/(g2c)=(ij/g2c)+(j/g)2 同时 g 是 j 的因数,所以 j 一定时, f’(i) 是以 d * j 为周期的等差数列,可以直接算。(注意首项为 i + k * j 首项,周期应为 c * j)
网上写的特别扯淡,明明 i 和 i+j 相邻两项的差有取整函数根本不能整块加起来的好吧,(不过这个相邻项的差根据我们的推论确实也是周期的)。
时间复杂度 O(Tm^2logm) ,非常卡常 (我的正解被卡了 qwq)。

#include<bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f3f3f3f3f
#define pi pair<int,int>
#define fi first
#define se second
using namespace std;
ll f(int i,int j,int &c) {
    while(j) {
        c++;
        int t=i%j;
        i=j;
        j=t;
    }
    return 1ll*c*i*i;
}
ll sum1(ll x) {
    return x*(x+1)/2;
}
signed main() {
//    freopen("data.in","r",stdin); 
//    freopen("own.out","w",stdout);
    int T,n,m,p; scanf("%d",&T);
    while(T--) {
        scanf("%d%d%d",&n,&m,&p);
        ll res=0;
        for(int i=1;i<=m;i++) {
            for(int j=1;j<=i&&j<=n;j++) {
                int c=0; ll ff=f(j,i,c); // f(j,i)
                //(j + ik) * i / ff
                for(int k=0;k<c;k++) {
                    if(j+k*i>n) break;
                    //等差数列求和啊啊啊 
                    //首项 qwq 
                    //(j + ik) * i / ff
                    ll a0=1ll*(j+k*i)*i/ff;
                    ll d=1ll*c*i*i/ff;  
                    //循环节是 c * i 啊啊啊 
                    ll num=(n-j-k*i)/(c*i)+1;
                    res=(res+a0%p*num%p+num*(num-1)/2%p*d%p)%p;
                }
            }
        }
        printf("%lld\n",res);
    }
}
posted @ 2021-08-25 11:10  仰望星空的蚂蚁  阅读(15)  评论(0)    收藏  举报  来源