模拟解方程,有点小繁琐,逻辑处理的时候一定要细心,测试数据下载:http://sharif.ir/~acmicpc/acmicpc03/index.html
#include<stdio.h>
#include<string.h>
#include<math.h>
static int calc(int a, int b, char op, int right)
{
if (!right)
return op == '+' ? a + b : a - b;
else
return op == '+' ? a - b : a + b;
}
int main()
{
int t;
char s[256];
scanf("%d", &t);
while (getchar() != '\n')
;
while (t--)
{
gets(s);
int right = 0, i, l = strlen(s), temp = 0, prev = 0, prevx = 0;
char c, op = '+';
for (i = 0; i < l; i++)
{
c = s[i];
if (c == '+' || c == '-')
{
prev = calc(prev, temp, op, right);
op = c;
temp = 0;
}
else if (c >= '0' && c <= '9')
{
temp = temp * 10 + c - '0';
}
else if (c == 'x')
{
if (!temp)
temp = 1;
prevx = calc(prevx, temp, op, right);
temp = 0;
}
else if (c == '=')
{
if (temp)
prev = calc(prev, temp, op, right);
right = 1;
temp = 0;
op = '+';
}
}
if (temp)
prev = calc(prev, temp, op, right);
if (!prevx)
puts(prev ? "IMPOSSIBLE" : "IDENTITY");
else
printf("%d\n", (int) floor(prev / (double) (-prevx)));
}
return 0;
}