1638: Continued Fraction
Time Limit: 1 Sec Memory Limit: 128 MB
Description
Input
Output
Sample Input
4 3 5 1 1 2 5 2 2
Sample Output
11 0 5 30 4 6 1 27
HINT
Source
解题:主要任务是把任一一个分数化成连分式。
方法就是分子分母同时不断的除以分子,直到分子为0。
至于加,减,乘,除都是先算出分数,然后把分数化成连分数。。
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long LL; 4 int n,m,a1[20],a2[20]; 5 LL gcd(LL x,LL y){ 6 return y?gcd(y,x%y):x; 7 } 8 void dfs(LL &A,LL &B,int *arr,int cur,int dep){ 9 if(cur == dep-1){ 10 A = arr[cur]; 11 B = 1; 12 } 13 if(cur >= dep-1) return; 14 LL tmpA,tmpB; 15 dfs(tmpA,tmpB,arr,cur+1,dep); 16 LL theGCD = gcd(A = arr[cur]*tmpA + tmpB,B = tmpA); 17 A /= theGCD; 18 B /= theGCD; 19 } 20 void print(LL x,LL y){ 21 LL GCD = gcd(x,y); 22 LL tmp = (x /= GCD)/(y /= GCD),p = x - tmp*y; 23 printf("%lld%c",tmp,p?‘ ‘:‘\n‘); 24 if(p) print(y,p); 25 } 26 int main(){ 27 while(~scanf("%d %d",&n,&m)){ 28 for(int i = 0; i < n; ++i) scanf("%d",a1+i); 29 for(int i = 0; i < m; ++i) scanf("%d",a2+i); 30 LL A1 = 0,B1 = 1,A2 = 0,B2 = 1; 31 dfs(B1,A1,a1,1,n); 32 dfs(B2,A2,a2,1,m); 33 A1 += a1[0]*B1; 34 A2 += a2[0]*B2; 35 print(A1*B2 + A2*B1,B1*B2); 36 print(A1*B2 - A2*B1,B1*B2); 37 print(A1*A2,B1*B2); 38 print(A1*B2,A2*B1); 39 } 40 return 0; 41 }
时间: 2024-12-28 08:12:27