BZOJ-2186: [Sdoi2008]沙拉公主的困惑(欧拉函数+乘法逆元)

题目:http://www.lydsy.com/JudgeOnline/problem.php?id=2186

由于(a+b,b)=(a,b),所以答案就是phi(m!)*n!/m!,然后化简之后上乘法逆元。

(第一次写乘法逆元居然1Y了。。。好开心~)

代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
 
using namespace std ;
 
#define MAXN 10000100
#define MAXT 10100
#define MAXP 4501000
 
#define rep( i , x ) for ( int i = 0 ; i ++ < x ; )
 
typedef long long ll ;
 
bool f[ MAXN ] ;
int p[ MAXP ] , pcnt = 0 ; 
int tot , R , maxn = 0 , q[ MAXT ][ 2 ] ;
 
ll mul[ MAXN ] , mulp[ MAXP ] , mul_p[ MAXP ] ;
 
struct Info {
    ll g , x , y ;
    Info( ll _g , ll _x , ll _y ) : g( _g ) , x( _x ) , y( _y ) {
    }
};
 
Info ex_gcd( ll a , ll b ) {
    if ( ! b ) return Info( a , 1 , 0 ) ;
    Info temp = ex_gcd( b , a % b ) ;
    return Info( temp.g , temp.y , temp.x - ( a / b ) * temp.y ) ;
}
 
int Search( int val ) {
    int l = 0 , r = pcnt + 1 , mid ;
    while ( r - l > 1 ) {
        mid = ( l + r ) >> 1 ; 
        if ( p[ mid ] <= val ) l = mid ; else r = mid ;
    }
    return l ; 
}
 
ll ins_mul( ll a , ll r ) {
    Info rec = ex_gcd( r , a ) ;
    if ( rec.y < 0 ) {
        rec.y += ( ( - rec.y ) / r ) * r ;
        if ( rec.y < 0 ) rec.y += r ;
    }
    return rec.y ;
}
 
void Solve( int n , int m ) {
    int pos = Search( m ) ;
    ll ans = ( ( mul[ n ] * mul_p[ pos ] ) % ll( R ) * ins_mul( mulp[ pos ] , ll( R ) ) ) % ll( R ) ;
    printf( "%lld\n" , ans ) ;
}
 
int main(  ) {
    scanf( "%d%d" , &tot , &R ) ;
    rep( i , tot ) {
        scanf( "%d%d" , &q[ i ][ 0 ] , &q[ i ][ 1 ] ) ;
        maxn = max( maxn , max( q[ i ][ 0 ] , q[ i ][ 1 ] ) ) ;
    }
    memset( f , true , sizeof( f ) ) ;
    f[ 1 ] = false ;
    rep( i , maxn ) if ( f[ i ] ) {
        p[ ++ pcnt ] = i ; 
        for ( int j = i << 1 ; j <= maxn ; j += i ) {
            f[ j ] = false ;
        }
    }
    mul[ 0 ] = mulp[ 0 ] = mul_p[ 0 ] = 1 ; 
    rep( i , maxn ) mul[ i ] = mul[ i - 1 ] * ll( i ) % ll( R ) ;
    rep( i , pcnt ) {
        mulp[ i ] = mulp[ i - 1 ] * ll( p[ i ] ) % ll( R ) ;
        mul_p[ i ] = mul_p[ i - 1 ] * ll( p[ i ] - 1 ) % ll( R ) ;
    }
    rep( i , tot ) Solve( q[ i ][ 0 ] , q[ i ][ 1 ] ) ;
    return 0 ; 
}
    原文作者:AmadeusChan
    原文地址: https://www.jianshu.com/p/e6b97493d15c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞