当前位置: 代码迷 >> 综合 >> 表达式树+多项式模拟 fzu2215 Simple Polynomial Problem
  详细解决方案

表达式树+多项式模拟 fzu2215 Simple Polynomial Problem

热度:15   发布时间:2023-12-14 03:13:56.0

传送门:点击打开链接

题意:化简多项式。

思路:先写个结构体,把多项式的乘法和加法重载好。

然后直接套后缀表达式啊,或者表达式树啊,或者用栈写表达式解析啊,都是随意的

下面这个是表达式树的写法。

有一个要注意的地方是,在函数里面开数组,也是属于栈的空间,所以用G++提交的时候,要注意一下扩栈。

#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#define fuck(x) cout<<"["<<x<<"]";
#define FIN freopen("input.txt","r",stdin);
#define FOUT freopen("output.txt","w+",stdout);
//#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;const int MX = 2e3 + 5;
const int mod = 1e9 + 7;struct Node {int len, s[MX];int &operator[](int i) {return s[i];}const int &operator [] (int i) const {return s[i];}Node operator+ (const Node &P) const {Node ret; memset(ret.s, 0, sizeof(ret.s));ret.len = max(len, P.len);for(int i = 0; i <= ret.len; i++) {ret[i] = ((LL)s[i] + P[i]) % mod;}return ret;}Node operator* (const Node &P) const {Node ret; memset(ret.s, 0, sizeof(ret.s));ret.len = len + P.len;for(int i = 0; i <= len; i++) {for(int j = 0; j <= P.len; j++) {ret[i + j] = (ret[i + j] + (LL)s[i] * P[j]) % mod;}}while(ret.len && !ret[ret.len]) ret.len--;return ret;}void print() {for(int i = len; i >= 0; i--) {printf("%d%c", s[i], i ? ' ' : '\n');}}
} A[MX];char op[MX];
int lch[MX], rch[MX], sz;int build(char *S, int L, int R) {int c[] = { -1, -1}, p = 0, u;int sign = true, isx = false, sum = 0;if(L == R) {u = ++sz;op[u] = '.';memset(A[u].s, 0, sizeof(A[u].s));if(S[L] == 'x') A[u].len = 1, A[u][1] = 1;else A[u].len = 0, A[u][0] = S[L] - '0';return u;}for(int i = L; i <= R; i++) {switch(S[i]) {case '(': p++; break;case ')': p--; break;case '+': if(!p) c[0] = i; break;case '*': if(!p) c[1] = i; break;}}if(c[0] < 0) c[0] = c[1];if(c[0] < 0) u = build(S, L + 1, R - 1);else {u = ++sz;op[u] = S[c[0]];lch[u] = build(S, L, c[0] - 1);rch[u] = build(S, c[0] + 1, R);}return u;
}Node solve(int u) {if(op[u] == '.') return A[u];Node al = solve(lch[u]), ar = solve(rch[u]);switch(op[u]) {case '+': return al + ar;case '*': return al * ar;}
}char W[MX];
int main() {int Size = 10240000;char *p = (char *)malloc(Size) + Size;__asm__("movl %0, %%esp\n" :: "r"(p));int T; //FIN;scanf("%d", &T);while(T--) {sz = 0;scanf("%s", W);int n = strlen(W);int rt = build(W, 0, n - 1);Node ret = solve(rt);ret.print();}return 0;
}


  相关解决方案