Polynomial Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 1133 Accepted Submission(s): 448
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).
![](https://i-blog.csdnimg.cn/blog_migrate/0eaf97f52afdd3ce338ce2b19cd5ad78.gif)
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
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.
Author
SmallBeer(CML)
Source
Recommend
lcy
模拟题实在是写的想死,BUG一大堆,忍不住就想看题解;
倒着模拟比较简单,因为如果正向模拟,表达式的首个字符可能是 - ,还可能没有,而倒着模拟,末尾一定是没有+或-号的;
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
#include<map>
#define LL long long
using namespace std;
char s[1010];
LL x;
//快速幂
LL quick(LL a,LL m)
{
LL sum=1;
while(m)
{
if(m&1)
sum*=a;
a*=a;
m>>=1;
}
return sum;
}
LL dfs(LL l,LL r)
{
LL flag=0,t_flag=0,ans=0,i,j,num1=0,num2=0;
for(i=l;i<=r;i++)
{
if(s[i]>='0'&&s[i]<='9')
{
num1=num1*10+s[i]-'0';
flag=1;
}
else if(s[i]=='X')
{
t_flag=1;
break;
}
}
if(!t_flag)return num1;
//如果num1为0,且flag=1,都没出现,系数默认为1,则将num变为1
if(!num1&&!flag)num1=1;
for(j=i+2;j<=r;j++)
{
if(s[j]>='0'&&s[j]<='9')
{
num2=num2*10+s[j]-'0';
}
}
//一个数的0次方为1
if(num2==0)num2=1;
return num1*quick(x,num2);
}
LL solve()
{
LL len=strlen(s),i,j,ans=0;
for(i=len-1;i>=0;i--)
{
for(j=i;j>=0;j--)
{
//由于表达式开头可能有-但一定没有+,所以判断-写前面
if(s[j]=='-')
{
ans-=dfs(j+1,i);
i=j;
break;
}
//判断+,如果搜到0,则直接加
else if(s[j]=='+'||j==0)
{
if(s[j]=='+')
ans+=dfs(j+1,i);
else
ans+=dfs(j,i);
i=j;
break;
}
}
}
return ans;
}
int main()
{
while(~scanf("%lld",&x))
{
scanf("%s",s);
printf("%lld\n",solve());
}
return 0;
}