当前位置: 代码迷 >> 综合 >> HDU 5912 - Fraction
  详细解决方案

HDU 5912 - Fraction

热度:79   发布时间:2023-12-24 11:18:42.0

题目大意:有t个样例,每个样例输入n,输入a1,a2,a3...an。输入b1,b2,b3....bn。输出按公式的计算结果。
解题思路:用递归,初始化a0 = 0,从最下层保存分子分母,每次计算分子分母,最后进行化简。

ac代码:

#include <iostream>
using namespace std;
int t, n, a[16], b[16], temp1, temp2, temp3, cnt=1;
void dfs(int cur)
{if (cur == n)temp1 = a[n], temp2 = b[n] + a[n] * a[n-1];else{dfs(cur+1);temp3 = b[cur] * temp1;temp1 = temp2;temp2 = temp3 + temp1 * a[cur-1];}
}
int main()
{scanf("%d", &t);while (t--){scanf("%d", &n);a[0] = 0;for (int i=1; i<=n; i++)scanf("%d", &a[i]);for (int i=1; i<=n; i++)scanf("%d", &b[i]);dfs(1);for (int i=temp1; i>=2; i--)if (temp1 % i == 0 && temp2 % i == 0)temp1 /= i, temp2 /= i;printf("Case #%d: %d %d\n", cnt++, temp2, temp1);}return 0;}