HDU - 5912 Fraction

HDU - 5912 Fraction

唔……学校的复活赛,连续三场名次加起来小于50才可以……这是第一次,不太乐观,排名17,做题数没优势,罚时发到哭。

Mr. Frog recently studied how to add two fractions up, and he came up with an evil idea to trouble you by asking you to calculate the result of the formula below:

As a talent, can you figure out the answer correctly?

Input
The first line contains only one integer T, which indicates the number of test cases.

For each test case, the first line contains only one integer n (n≤8).

The second line contains n integers: a1,a2,⋯an(1≤ai≤10).
The third line contains n integers: b1,b2,⋯,bn(1≤bi≤10).
Output
For each case, print a line “Case #x: p q”, where x is the case number (starting from 1) and p/q indicates the answer.

You should promise that p/q is irreducible.
Sample Input
1
2
1 1
2 3
Sample Output
Case #1: 1 2

Hint
Here are the details for the first sample:
2/(1+3/1) = 1/2

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm> 
#include<cstring>
#include<string>
#define N 510
#define INF 0x3f3f3f3f
using namespace std; 
int gcd(int a,int b)      
{
    if(a%b==0)  
        return b;           
    else                   
        return gcd(b,a%b);     
} 

int a[20],b[20];
int main()
{
    int t,i,n,p,q,k,m,ans;//p上q下 
    ans=0;
    scanf("%d",&t);
    while(t--){
        ans++;
        scanf("%d",&n);
        for(i=1;i<=n;i++){
            scanf("%d",&a[i]);
        }
        for(i=1;i<=n;i++){
            scanf("%d",&b[i]);
        }
        p=b[n];
        q=a[n];
        k=gcd(p,q);
        p=p/k;
        q=q/k;
        for(i=n-1;i>0;i--){
            p=q*a[i]+p;
            k=gcd(p,q);
            p=p/k;
            q=q/k;
            m=p;
            p=q*b[i];
            q=m;
            k=gcd(p,q);
            p=p/k;
            q=q/k;
        }
        printf("Case #%d: %d %d\n",ans,p,q); 
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/mandiheyanyu/article/details/82429229
今日推荐