Polynomial Problem
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.
ps:直接模拟即可,注意n的取值范围
代码:
#include<stdio.h>
#include<string.h>
typedef long long int LL;
char a[1010];
LL pow(LL x,LL y)
{
LL sum=1;
for(LL i=1; i<=y; i++)
sum*=x;
return sum;
}
int main()
{
LL x;
while(~scanf("%lld",&x))
{
scanf("%s",a);
LL len=strlen(a);
LL ans=0,cnt,tot,flag,flog1,flog2;
for(LL i=0; i<len; i++)
{
flog1=0,flog2=0;
if(a[i]=='-')
flag=1,i++;
else
{
flag=0;
if(a[i]=='+')
i++;
}
if(a[i]>='0'&&a[i]<='9'&&i<len)
{
flog1=1;
cnt=0;
while(a[i]>='0'&&a[i]<='9'&&i<len)
{
cnt=cnt*10+(a[i]-'0');
i++;
}
}
if(a[i]=='X'&&i<len)
{
flog2=1;
if(a[i+1]=='^')
{
i+=2;
LL t=0;
while(a[i]>='0'&&a[i]<='9'&&i<len)
{
t=t*10+(a[i]-'0');
i++;
}
i--;
tot=pow(x,t);
}
else
tot=x;
}
if(flag)
{
if(flog1&&flog2)
ans-=cnt*tot;
else if(flog1)
ans-=cnt;
else if(flog2)
ans-=tot;
}
else
{
if(flog1&&flog2)
ans+=cnt*tot;
else if(flog1)
ans+=cnt;
else if(flog2)
ans+=tot;
}
}
printf("%lld\n",ans);
}
return 0;
}
ps:比赛时做了一个多小时就是找不出哪里错误,结果一看别人的代码,原来是没有看到n的范围,我把n当成了个一位数0.0。。
总结:做题时一定要细心,注意每一个值的取值范围,卡题一个多小时这种情况一般就是一些极限数据有些错误