您的位置:首页 > 其它

FZU_1753 Another Easy Problem

2012-05-21 23:41 363 查看
http://acm.fzu.edu.cn/problem.php?pid=1753

题意:

其实就是求N个组合数的最大公约数。

思路:

C(n , m) = n! / (n- m)! * m! ,因此求这些组合数的最大公约数, 我们只需要先将每个组合数

进行因式分解,所有求出所有组合数的每个因子的最小值相乘即可。现在的问题就是如何

高效地进行组合数的因式分解,对于n!的因式分解,我们可以这样考虑,首先筛选出所有

1-n的素数,然后对于一个素数p[i],1-n中有因子p[i]的一定是形如:p[i]*1, 2*p[i] ,3*p[i] ,...

第一轮我们得到的是 n / p[i]个因子,并且将n变成n/p[i],这样一直到n等于0的时候就可以求

出所有n!的p[i]的因子了。

代码:

#include<stdio.h>
#include<string.h>
#define CC(m,what) memset(m ,what , sizeof(m))
int N ;
const int MAXN = 100010 ;
const int NN = 155 ;
bool is_p[MAXN] ;
int p[MAXN] , cnt ;
long long A[NN] , B[NN] ;
int num[MAXN] ;
int minnum ;

void calc(){
cnt = 0 ;
for(int i=1;i<MAXN;i++) is_p[i] = 1 ;
is_p[1] = 0;
for(int i=2;i<MAXN;i++){
if( is_p[i] == 0)   continue ;
p[cnt++] = i ;
for(int j=2;j*i<MAXN;j++){
is_p[ i*j ] = 0 ;
}
}
}

void cal(long long n1, long long n2 , long long n3 , int d){        //对n1! , n2! , n3!分解质因数
long long temp ;
for(int i=0;i<cnt && p[i]<=minnum;i++){
int c = 0 ;
if( p[i] <= n1 ){
temp = n1 ;
while(temp){
c += temp/p[i] ; temp /= p[i] ;
}
}
if( p[i] <= n2 ){
temp = n2 ;
while(temp){
c -= temp/p[i] ; temp /= p[i] ;
}
}
if( p[i] <= n3 ){
temp = n3 ;
while(temp){
c -= temp/p[i] ; temp /= p[i] ;
}
}
if( d == 1 ){
num[i] = c ;
}
else{
num[i] = num[i] > c ? c : num[i] ;
}
}
}

void solve(){
CC(num , 0 );
for(int i=1;i<=N;i++){
cal( A[i] , B[i] , A[i]-B[i] , i) ;
}
long long res = 1 ;
for(int i=0;i<cnt;i++){
if( num[i] != 0 ){
for(int j=1;j<=num[i] ;j++){
res *= p[i] ;
}
}
}
printf("%I64d\n",res);
}

int main(){
calc() ;
while(scanf("%d",&N) == 1){
minnum = MAXN ;
for(int i=1;i<=N;i++){
scanf("%I64d %I64d",&A[i],&B[i]);
if( A[i] < minnum ) minnum = A[i] ;
}
solve() ;
}
return 0 ;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: