一.题目链接:
ZOJ-3999
二.题目大意:
读入有三行
一行分子表达式
一行分母表达式
一行 取值
求出
三.分析:
表达式读入有些麻烦
具体见代码.
注意:题目中没有保证指数是有序排列的!
四.代码实现:
#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-6
#define pi acos(-1.0)
#define ll long long int
using namespace std;
struct node
{
ll coef;
ll expn;
} p[2][20];
void get_(string s, ll id)
{
ll cnt = 0;
ll coef = 1;
ll expn = 1;
bool flag = 1;
ll len = s.size();
for(ll i = 0; i < len; ++i)
{
if(s[i] == '-')
{
coef *= -1;
}
else if(s[i] >= '0' && s[i] <= '9')
{
if(flag)
{
coef *= s[i] - '0';
flag = 0;
if(i == len - 1 || s[i + 1] == '+' || s[i + 1] == '-')
{
p[id][cnt].coef = coef;
flag = 1;
expn = 1;
coef = 1;
cnt++;
}
}
else
{
expn *= s[i] - '0';
p[id][cnt].expn = expn;
cnt++;
flag = 1;
expn = 1;
coef = 1;
}
}
else if(s[i] == 'x')
{
p[id][cnt].coef = coef;
flag = 0;
if(i == len - 1 || s[i + 1] != '^')
{
p[id][cnt].expn = 1;
flag = 1;
expn = 1;
coef = 1;
cnt++;
}
}
}
}
ll quick(ll a, ll b)
{
ll sum = 1;
while(b)
{
if(b & 1)
sum *= a;
a *= a;
b >>= 1;
}
return sum;
}
void cal(ll &value1, ll &value2, ll x)
{
value1 = value2 = 0;
for(ll i = 0; i < 15; ++i)
{
value1 += p[0][i].coef * quick(x, p[0][i].expn);
value2 += p[1][i].coef * quick(x, p[1][i].expn);
}
}
void luo()
{
for(ll i = 0; i < 15; ++i)
{
p[0][i].coef *= p[0][i].expn;
p[0][i].expn--;
if(p[0][i].expn == -1)
p[0][i].coef = p[0][i].expn = 0;
p[1][i].coef *= p[1][i].expn;
p[1][i].expn--;
if(p[1][i].expn <= -1)
p[1][i].coef = p[1][i].expn = 0;
}
}
void print(ll value1, ll value2, ll x)
{
cal(value1, value2, x);
if(value1 && value2)
{
if(value1 % value2 == 0)
cout << value1 / value2 << "\n";
else
{
ll gcd = __gcd(value1, value2);
if(value1 * value2 > 0)
cout << value1 / gcd << "/" << value2 / gcd << "\n";
else
cout << "-" << (ll)abs(value1 / gcd) << "/" << (ll)abs(value2 / gcd) << "\n";
}
}
else if(value1 && !value2)
cout << "INF\n";
else if(!value1 && value2)
cout << "0\n";
else
{
luo();
print(value1, value2, x);
}
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
string s1, s2;
ll x;
cin >> s1 >> s2 >> x;
memset(p,0, sizeof(p));
get_(s1, 0);
get_(s2, 1);
ll value1, value2;
print(value1, value2, x);
}
return 0;
}