首页 > ACM题库 > HDU-杭电 > Hdu 1296 Polynomial Problem-模拟-[解题报告] C++
2013
12-04

Hdu 1296 Polynomial Problem-模拟-[解题报告] C++

Polynomial Problem

问题描述 :

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).

输入:

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

输出:

For each test case, there is only one integer means the value of f(x).

样例输入:

3
1003X^5+234X^4-12X^3-2X^2+987X-1000

样例输出:

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.

思路:一个数学的算术表达式,比较简单的,主要是注意处理头尾的,接着就是耐心打代码了。
代码如下:
#include 
#include 
#include 
using namespace std;

char str[100005],temp;
__int64 top,flag,i,len,sum,s1,s2;

__int64 fun(__int64 x,__int64 y)
{
	int k;
	__int64 sum1=1;
	for(k=1;k&lt;=y;k++)
		sum1*=x;
	return sum1;
}

int main()
{
	__int64 x;
	while(scanf("%I64d%s",&amp;x,str)!=EOF)
	{
		s1=s2=0;
		len=strlen(str);
		top=-1;
		sum=0;
		temp='+';
		i=0;
		while(i&lt;=len)
		{
			if(str[i]=='+' || str[i]=='-' || str[i]=='/0')
			{
				if(temp=='+')
					sum+=s1*fun(x,s2);
				else
					sum-=s1*fun(x,s2);
				s1=s2=0;
				flag=0;
				temp=str[i];
				i++;
			}
			else if(str[i]=='X') 
			{
				if(s1==0)
					s1=1;
				i++;
				if(str[i]!='^')
					s2=1;
			}
			else if(str[i]=='^')
			{
				i++;
				while(1)
				{
					if(str[i]=='+' ||str[i]=='-' || str[i]=='/0')
						break;
					else
						s2=s2*10+str[i]-'0';
					i++;
				}
			}
			else
			{
				s1=s1*10+str[i]-'0';
				i++;
			}
		}
		printf("%I64d/n",sum);
	}
	return 0;
}

 


  1. 第23行:
    hash = -1是否应该改成hash[s ] = -1

    因为是要把从字符串s的start位到当前位在hash中重置

    修改提交后能accept,但是不修改居然也能accept