【模拟题、表达式求值】hdu hdoj 1296 Polynomial Problem

 

一题模拟题,主要要注意细节的处理。

yb牛写一遍就过了,,,,ym.....

自己wa了一个晚上。。。。。

具体方法看注释就懂了。。。

#include <stdlib.h> #include <stdio.h> #include <string.h> typedef __int64 TYPE; TYPE xx[15]; char str[10005], s[10005]; void get(int x) { __int64 i, t = x; xx[0] = 1; for(i = 1; i<=10; i++) { xx[i] = t; t *= x; } } TYPE solve() { TYPE ans, c1, c2, n; int i, len = strlen(s); int op = 0;//+ 1 | - 2 bool flag, flag2; i = 0, c1 = 0, c2 = 0, n = 0, ans = 0, flag = false; while(i<=len) { if( s[i] == '+' || s[i] == '-' || s[i] == 0x00) { c2 = xx[n]; //根据操作符进行运算 if(op == 1) { ans += (c1 * c2); flag = false; //printf( "ans:%I64d/n", c1*c2); } if(op == 2) { ans -= (c1 * c2); flag = false; //printf( "ans:-%I64d/n", c1*c2); } //首先读取操作符 if(s[i] == '+') op = 1; if(s[i] == '-') op = 2; i++; c1 = 0, c2 = 0, n = 0; } else { //读取X前面的数字 if(s[i] >= '0' && s[i] <= '9') { flag = true; c1 = c1*10 + s[i] - '0'; i++; } if(s[i] == 'X') { //前缀为空 if(c1 == 0 && flag == false) c1 = 1; i++; //X的后缀为空 if (s[i] != '^') n = 1; } if(s[i] == '^') { i++; //读取^后面的数字 while(1) { if(s[i] == '+' || s[i] == '-' || s[i] == 0x00) break; n = n*10 + s[i] - '0'; i++; } } } } //printf("#%d/n", ans); return ans; } /* * */ int main() { int x; while(scanf("%d%s", &x, str) != EOF) { get(x); if(str[0] != '-') { //所有字符串前缀都以符号开始,比较好处理 s[0] = '+'; strcpy(&s[1], str); } else { strcpy(s, str); } printf("%I64d/n", solve()); } return 0; }

Polynomial Problem Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 216 Accepted Submission(s): 101 Problem Description We have learned how to obtain the value of a polynomial when we were a middle school student. If f(x) is a polynomial of degree n, we can let If we have x, we can get f(x) easily. But a computer can not understand the expression like above. So we had better make a program to obtain f(x). Input There are multiple cases in this problem and ended by the EOF. In each case, there are two lines. One is an integer means x (0<=x<=10000), the other is an expression means f(x). All coefficients ai(0<=i<=n,1<=n<=10,-10000<=ai<=10000) are integers. A correct expression maybe likes 1003X^5+234X^4-12X^3-2X^2+987X-1000 Output For each test case, there is only one integer means the value of f(x). Sample Input 3 1003X^5+234X^4-12X^3-2X^2+987X-1000 Sample Output 264302 Notice that the writing habit of polynomial f(x) is usual such as X^6+2X^5+3X^4+4X^3+5X^2+6X+7 -X^7-5X^6+3X^5-5X^4+20X^3+2X^2+3X+9 X+1 X^3+1 X^3 -X+1 etc. Any results of middle process are in the range from -1000000000 to 1000000000.

 

你可能感兴趣的:(【模拟题、表达式求值】hdu hdoj 1296 Polynomial Problem)