HDU5912 Fraction(模拟)

来源:互联网 发布:怎样申请淘宝企业店铺 编辑:程序博客网 时间:2024/06/05 14:22

Problem Description

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

121 12 3

Sample Output

Case #1: 1 2

Hint

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

思路

如图,题目给了从a[1~n],b[1~n],让你按照图中的方法化简一下式子,最后输出这个式子的最终结果的分子和分母

我们分析一下这个式子,最底下那一个式子可以改写为:

an1+bnan1

所以我们令初始分母为1,分子为a[n],然后进行模拟。

到了最后会出现这样一种情况,转化一下即可:

b1fzfm=b1fmfz

代码:

#include<cstdio>#include<cstring>#include<string>#include<set>#include<iostream>#include<stack>#include<queue>#include<vector>#include<algorithm>#define mem(a,b) memset(a,b,sizeof(a))#define inf 0x3f3f3f3f#define mod 10000007#define debug() puts("what the fuck!!!")#define ll long longusing namespace std;int a[20],b[20];int main(){    int t,n,q=1;    scanf("%d",&t);    while(t--)    {        scanf("%d",&n);        for(int i=1; i<=n; i++)            scanf("%d",&a[i]);        for(int i=1; i<=n; i++)            scanf("%d",&b[i]);        int tmp,fz=a[n],fm=1;        for(int i=n-1; i>=1; i--)        {            tmp=a[i]*fz+b[i+1]*fm;            fm=fz;            fz=tmp;        }        fm=b[1]*fm;        int k=__gcd(fm,fz);        printf("Case #%d: %d %d\n",q++,fm/k,fz/k);    }    return 0;}