@ysner
2018-08-04T17:31:12.000000Z
字数 2507
阅读 2063
中缀表达式
模拟
给出一个表达式,其中包含有数字、未知数、、、和括号。把它化简成的形式。系数模。
显然直接模拟。
对于直接求中缀表达式的值:
如果加上了未知数,就把数字栈变为多项式栈,用结构体储存所有项的系数,模拟一般多项式运算即可。复杂度上限
听起来很简单是吧。然而我调了2h
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#define re register
#define il inline
#define ll long long
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define fp(i,a,b) for(re int i=a;i<=b;i++)
#define fq(i,a,b) for(re int i=a;i>=b;i--)
using namespace std;
const int mod=10007;
char s[1005],sta[1005];
int len,top,tot,id[1005];
struct dui
{
ll x[1005],mx;
il dui(){memset(x,0,sizeof(x));mx=0;}
}a[1005];
il void check(re ll &x) {while(x<0) x+=mod;if(x>=mod) x%=mod;}
il dui operator *(dui A,dui B)
{
dui C;
fp(i,0,A.mx)
fp(j,0,B.mx)
{
C.x[i+j]+=A.x[i]*B.x[j];
check(C.x[i+j]);
}
C.mx=A.mx+B.mx;while(C.x[C.mx]==0&&C.mx) --C.mx;
return C;
}
il dui operator +(dui A,dui B)
{
dui C;
fp(i,0,max(A.mx,B.mx))
{
C.x[i]=A.x[i]+B.x[i];
check(C.x[i]);
}
C.mx=max(A.mx,B.mx);while(C.x[C.mx]==0&&C.mx) --C.mx;
return C;
}
il dui operator -(dui A,dui B)
{
dui C;
fp(i,0,max(A.mx,B.mx))
{
C.x[i]=A.x[i]-B.x[i];
check(C.x[i]);
}
C.mx=max(A.mx,B.mx);while(C.x[C.mx]==0&&C.mx) --C.mx;
return C;
}
il ll gi()
{
re ll x=0,t=1;
re char ch=getchar();
while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if(ch=='-') t=-1,ch=getchar();
while(ch>='0'&&ch<='9') x=x*10+ch-48,ch=getchar();
return x*t;
}
il int check(re char x,re char y)
{
if(x=='(') return 1;if(x==')') return 0;
return id[x]>id[y];
}
il void calc(re dui &x,re dui y,re char p)
{
if(p=='+') x=x+y;
if(p=='-') x=x-y;
if(p=='*') x=x*y;
}
int main()
{
freopen("simplify.in","r",stdin);
freopen("simplify.out","w",stdout);
scanf("%s",s+1);len=strlen(s+1);s[++len]='#';
id['+']=id['-']=2;id['*']=3;id['#']=-1;id['?']=-2;sta[0]='?';
fp(i,1,len)
{
if(s[i]>='0'&&s[i]<='9')
{
if(s[i-1]>='0'&&s[i-1]<='9') a[tot].x[0]=a[tot].x[0]*10+s[i]-'0';
else a[++tot].mx=0,memset(a[tot].x,0,sizeof(a[tot].x)),a[tot].x[0]=s[i]-'0';
}
else if(s[i]=='x') memset(a[++tot].x,0,sizeof(a[tot].x)),a[tot].mx=1,a[tot].x[1]=1;
else
{
if(check(s[i],sta[top])) sta[++top]=s[i];
else
{
if(s[i]==')')
{
while(sta[top]!='(') {
calc(a[tot-1],a[tot],sta[top]);--tot;--top;}
--top;
}
else
{
while(!check(s[i],sta[top])) {
calc(a[tot-1],a[tot],sta[top]);--tot;--top;
}
sta[++top]=s[i];
}
}
}
}
printf("%lld\n",a[1].mx);
fp(i,0,a[1].mx) printf("%lld\n",a[1].x[i]%mod);
fclose(stdin);
fclose(stdout);
return 0;
}