两个栈,一个符号栈(zhan1),一个多项式栈(zhan)。
zhan[i][j]:表示第i个多项式第j次项的系数。
遇到')',把它到上一个‘(’之间的‘+’,‘-’,‘*‘’全都处理出来。
优先级:'*' >'+','-' >'(',')'
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int mod = 10007;
long long zhan[1010][1010], top, num, g[1010], tmp[1010],n;
char s[1010],zhan1[1010];
long long add(long long x,long long y){x += y; if(x > mod) x -= mod; if(x < 0) x += mod; return x;}//取模操作
int youx(char c)//判断优先级
{
if(c == '*') return 2;
if(c == '-' || c == '+') return 1;
return 0;
}
void chuli()
{
if(zhan1[num] == '+')//多项式加法
{
for(int i =0; i <= n; i++)
zhan[top-1][i] = add(zhan[top-1][i],zhan[top][i]); top--;
}
if(zhan1[num] == '-')//多项式减法
{
for(int i =0; i <= n; i++)
zhan[top-1][i] = add(zhan[top-1][i], -zhan[top][i]); top--;
}
if(zhan1[num] == '*')//多项式乘法
{ int cnt = 0; memset(tmp,0,sizeof(tmp));
for(int i = 0; i <= n; i++)
if(zhan[top][i]) g[++cnt] = i;
for(int i = 0; i <= n; i++)
{ if(zhan[top-1][i])
for(int j = 1; j <= cnt; j++)
tmp[i + g[j]] = add(tmp[i + g[j]],zhan[top-1][i] * zhan[top][g[j]] % mod);
}
for(int i = 0; i <= n; i++) zhan[top-1][i] = tmp[i];
top--;
} num--;
}
int main()
{
scanf("%s",s); n = strlen(s)-1;
for(int i = 0; i <= n; i++)
{
if(s[i] == '(') zhan1[++num] = '(';
else if(s[i] == ')')//是 ')'把它到上一个‘(’之间的‘+’,‘-’,‘*‘’全都处理出来。
{while(zhan1[num] != '(') {chuli();} num--;}
else if(s[i] == 'x')
{ top++; memset(zhan[top],0,sizeof(zhan[top])); zhan[top][1] = 1; }
else if(s[i] >= '0' && s[i] <= '9')
{ long long x = 0;
while(s[i] >= '0' && s[i] <= '9'){x = x * 10 + s[i] - '0'; i++;} i--;
top++;memset(zhan[top],0,sizeof(zhan[top])); zhan[top][0] = x % mod;
}
else if(s[i] == '-' || s[i] == '+' || s[i] == '*')
{ while(youx(s[i]) <= youx(zhan1[num])){chuli();} zhan1[++num] = s[i]; }
}
while(num) chuli(); int ans = 0; //如果还有没处理的符号,处理。
for(int j = n; j >= 0; j--)//处理完后,只有一个多项式了。第一个
if(zhan[1][j]) { ans =max(j,ans); break;} printf("%d\n",ans);
for(int j = 0; j <= ans; j++)
{printf("%lld\n",zhan[1][j] ); }
return 0;
}