Result: Accepted
Time: 6ms
Memory: 1708kB
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define N 20
int n, m;
string s1[N], s2[N];
ll gcd(ll a, ll b) {
return b == 0 ? a : gcd(b, a % b);
}
bool judge_number(string s) {
int i = (s[0] == '-');
for (int len = s.length(); i < len; ++i) {
if (s[i] < '0' || s[i] > '9') {
return false;
}
}
return true;
}
ll get_number(string s) {
ll res = 0;
int i = (s[0] == '-');
for (int len = s.length(); i < len; ++i) {
res = res * 10 + (s[i] - '0');
}
if (s[0] == '-') {
res = -res;
}
return res;
}
ll f(string s) {
ll res = 0;
int i = 2 + (s[2] == '-');
for (int len = s.length(); i < len; ++i) {
res = res * 10 + (s[i] - '0');
}
if (s[2] == '-') {
res = -res;
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t--) {
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
cin >> s1[i];
}
for (int i = 1; i <= m; ++i) {
cin >> s2[i];
}
ll up_number = 1, up_coef = 0, down_number = 1, down_coef = 0;
for (int i = 1; i <= n; ++i) {
if (judge_number(s1[i])) {
up_number *= get_number(s1[i]);
} else if (s1[i] == "sinx" || s1[i] == "arcsinx" || s1[i] == "tanx" || s1[i] == "arctanx" ||
s1[i] == "e^x-1" || s1[i] == "ln(x+1)" || s1[i] == "x") {
up_coef++;
} else if (s1[i] == "1-cosx") {
down_number *= 2;
up_coef += 2;
} else {
up_coef += f(s1[i]);
}
}
for (int i = 1; i <= m; ++i) {
if (judge_number(s2[i])) {
down_number *= get_number(s2[i]);
} else if (s2[i] == "sinx" || s2[i] == "arcsinx" || s2[i] == "tanx" || s2[i] == "arctanx" ||
s2[i] == "e^x-1" || s2[i] == "ln(x+1)" || s2[i] == "x") {
down_coef++;
} else if (s2[i] == "1-cosx") {
up_number *= 2;
down_coef += 2;
} else {
down_coef += f(s2[i]);
}
}
if (up_coef == down_coef) {
ll g = gcd(up_number, down_number);
up_number /= g, down_number /= g;
if ((up_number < 0 && down_number > 0) || (up_number > 0 && down_number < 0)) {
cout << "-";
}
if (abs(down_number) == 1) {
cout << abs(up_number) << "\n";
} else {
cout << abs(up_number) << "/" << abs(down_number) << endl;
}
} else if (up_coef > down_coef) {
cout << "0\n";
} else {
cout << "INF\n";
}
}
return 0;
}