fzu2215 中缀表达式展开求多项式系数(模拟)【中缀转后缀模板】

 (1+x)*(1+x) would be written as x^2+2*x+1.求每一项的系数。

visualC++过,G++超时。

#include <iostream>
#include <stack>
#include <string>
#include <cstdio>
#define ll long long
#define mod 1000000007
using namespace std;
struct node{
	ll a[200];
	node(){
		memset(a,0,sizeof(a));
	}
};
stack<node> st1;
stack<char> st2;
//中缀转后缀【数字限一位】 
int cmp(char ch)      // 运算符优先级 
{
	switch(ch)
	{
		case '+':
		case '-': return 1;
		case '*':
		case '/': return 2;
		default : return 0;
	}
}
void fun(char *a, string &b)      // 中缀式转变后缀式 
{
	stack <char> s;
	s.push('#');
	int i = 0;
	while(i < strlen(a) )
	{
		if(a[i] == '(')
		{
			s.push(a[i]);
			i++;
		}
		else if(a[i] == ')')
		{
			while(s.top() != '(')
			{
				b+= s.top();
//				b+= ' ';
				s.pop();
			}
			s.pop();
			i++;
		}
		else if(a[i] == '+'||a[i] == '-'||a[i] == '*'||a[i] == '/')
		{
			while(s.size()>0&&cmp(s.top()) >= cmp(a[i]))
			{
				if(s.top()!='(')
					b+= s.top();
//				b+= ' ';
				s.pop();
			}
			s.push(a[i]);
			i++;
		}
		else
		{
			if('0' <= a[i]&&a[i] <= '9'||a[i] == '.'||a[i]=='x') //最后一项因题而异 
			{
				b+= a[i];
				i++;
			}
//			b+= ' ';
		}
	}
	while(s.size()>0&&s.top() != '#')
	{
		if(s.top()!='(')
			b+= s.top();
//		b+= ' ';
		s.pop();
	}
//	b+= '=';
}
int ismark(char c){
	if(c=='+'||c=='*')
		return 1;
	else
		return 0;
}
int main()
{
	int n;
	scanf("%d",&n);
	while(n--)
	{
		char a[1005];
		string x="";	
		while(!st1.empty())
			st1.pop();
		while(!st2.empty())
			st2.pop();	
		scanf("%s",a);
		fun(a,x);
		for(int i=0;i<x.length();++i){
			if(!ismark(x[i])){
				node p;         
				if(x[i]=='x')   
					p.a[1]=1;  
				else            
					p.a[0]=x[i]-'0';   
				st1.push(p);  
			}
			else{
				node p1=st1.top();
				st1.pop();
				node p2=st1.top();
				st1.pop();
				node p3;
				if(x[i]=='*'){
					for(int i=0;i<100;++i){
						for(int j=0;j<100;++j){
							p3.a[i+j]=(p3.a[i+j]+p1.a[i]*p2.a[j])%mod;
						}
					}
				}
				else{
					for(int i=0;i<100;++i){
						p3.a[i]=(p1.a[i]+p2.a[i])%mod;
					}
				}
				st1.push(p3);
			}
			
		}
		node p=st1.top();
		int i;
		for(i=199;i>=0;--i)
			if(p.a[i]>0)
				break;
		for(int j=i;j>0;--j){
			printf("%d ",p.a[j]);
		}
		printf("%d\n",p.a[0]);
	}
	return 0;
}        


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值