HDU 5970 (循环节)

题目链接:点击这里

打个表可以发现对于给定的j,f(i,j)的循环节长度为j。有了这个性质以后可以处理不向下取整的。题目需要向下取整,谕示考虑f(i,j)的含义,它表示辗转相除次数c和gcd(i,j)的平方的乘积。因为(i+kj, j)和(i,j)的辗转次数相等,所以考虑延长循环节,把cj看成是循环节,这样的话就只需要求出循环节内部分,并且重复循环节就行了。在两个循环节之间是等差数列,瞎搞搞就出来了。

#include 
#define Clear(x,y) memset (x,y,sizeof(x))
#define FOR(a,b,c) for (int a = b; a <= c; a++)
#define REP(a,b,c) for (int a = b; a >= c; a--)
#define first fi
#define second se
#define pii pair
#define pli pair
#define mp make_pair
#define pb push_back
#define mod 1000000007
using namespace std;
#define maxn 667

long long f[maxn][maxn], c[maxn][maxn];
long long n, m, p;

long long gcd (long long x, long long y, long long &c) {
    c = 0;
    while (y) {
        c++;
        long long tmp = x%y;
        x = y;
        y = tmp;
    }
    return c*x*x;
}

void init () {
    memset (f, 0, sizeof f);
    for (int i = 1; i < maxn; i++) {
        for (int j = 1; j < maxn; j++) {
            long long tmp;
            f[i][j] = gcd (i, j, tmp);
            c[i][j] = tmp;
        }
    }
}

long long tmp[maxn];
int main () {
    //freopen ("more.in", "r", stdin);
    init ();
    int t;
    scanf ("%d", &t);
    while (t--) {
        scanf ("%lld%lld%lld", &n, &m, &p);
        long long ans = 0;
        for (long long j = 1; j <= m; j++) {
            for (long long i = 1; i <= j; i++) { 
                long long res = 0;
                for (int k = 0; k < c[i][j]; k++) {
                    tmp[k] = (i*j+j*j*k)/f[i][j] % p;
                    res = (res + tmp[k]) % p;
                } 
                long long tot = (n-i)/j; tot++; 
                long long T = tot/c[i][j]; 
                long long g = __gcd (i, j);
                ans = (ans + T*(T-1)/2%p*(j/g*j/g)%p*c[i][j]%p + res*T) % p;
                long long Max = tot-T*c[i][j];
                for (int k = 0; k < Max; k++) {
                    ans = (ans + tmp[k] + T*j/g*j/g%p) % p;
                }
            }
        }
        printf ("%lld\n", ans);
    }
    return 0;
}

你可能感兴趣的:(数论/推导)