A DP Problem (字符串处理+模拟)

来源:互联网 发布:武汉茶港大院 知乎 编辑:程序博客网 时间:2024/06/18 18:36

In this problem, you are to solve a very easy linear equation with only one variable x with no parentheses! An example of such equations is like the following:

2x - 4 + 5x + 300 = 98x

An expression in its general form, will contain a '=' character with two expressions on its sides. Each expression is made up of one or more terms combined by '+' or '-' operators. No unary plus or minus operators are allowed in the expressions. Each term is either a single integer, or an integer followed by the lower-case character x or the single character x which is equivalent to 1x.

You are to write a program to find the value of x that satisfies the equation. Note that it is possible for the equation to have no solution or have infinitely many. Your program must detect these cases too.

input

The first number in the input line, t (1 ≤ t ≤ 10) is the number of test cases, followed byt lines of length at most 255 each containing an equation. There is no blank character in the equations and the variable is always represented by the lower-case character x. The coefficients are integers in the range (0 ... 1000) inclusive.

output

The output contains one line per test case containing the solution of the equation. If s is the solution to the equation, the output line should contain |_s_| (the floor of s, i.e., the largest integer number less than or equal to s). The output should be "IMPOSSIBLE" or "IDENTITY" if the equation has no solution or has infinite solutions, respectively. Note that the output is case-sensitive.

sample input

2
2x-4+5x+300=98x
x+2=2+x

sample output

3
IDENTITY

本来以为是一个DP的题目,结果发现是一个模拟,和之前做的page count差不多,
都是对字符串处理的模拟。 注意的就是要向下取整,直接使用floor函数就可以。
x+2=x-2类似这样的都是无解的,之前没有考虑到不可能的情况。 

#include<cstdio>#include<cstring>#include<cstring>#include<cmath>#include<cstdlib>using namespace std; int main(){int t,a,X,Y,flag;char s[300],*p,*q;scanf("%d",&t);while(t--){scanf("%s",s);q=p=s;X=Y=0;flag=1;while(flag){a=0;if(*p>='0'&&*p<='9'){q=p;while(*p>='0'&&*p<='9'){a*=10;a+=*p-'0';p++;}if(*p=='=')flag=0;}if(*p=='x'){if (q==s||*(q-1)=='+')X+=a;else X-=a;}else{if(q==s||*(q-1)=='+')Y+=a;else Y-=a;}p++;if(*p=='=')flag=0;}if(*p!='=')p--;while (*p++){a=0;if(*p>='0'&&*p<='9'){q=p;while(*p>='0'&&*p<='9'){a*=10;a+=*p-'0';p++;}}if(*p=='x'){if(*(q-1)=='='||*(q-1)=='+')X-=a;else X+=a;}else{if(*(q-1)=='='||*(q-1)=='+')Y-=a;else Y+=a;}}p=s;while(*p!='='){    if(*p=='x'){if(p==s)X+=1;else if(*(p-1)=='+')X+=1;else if(*(p-1)=='-')X-=1;}p++;}while(*p++){    if(*p=='x'){if(*(p-1)=='=')X-=1;else if(*(p-1)=='+')X-=1;else if(*(p-1)=='-')X+=1;}}if(X==0&&Y==0){printf("IDENTITY\n");}else if(X==0&&Y!=0){printf("IMPOSSIBLE\n");} else{printf("%d\n",(int)floor(Y*1.0/-X));}}}