[C/C++]OJ练习题:一元稀疏多项式计算器

来源:互联网 发布:淘宝花呗分期退货 编辑:程序博客网 时间:2024/06/01 22:46

>题目

   多组数据,第一行为N,表示有N组数据;接下来的N组数据,每三行为一组:第一行为n,m,t三个数字(int,下同),n为第一个多项式的项数、m为第二个多项式的项数、t为计算模式(为1时,第一个多项式减第二个多项式;为0时两个多项式相加);第二行为2n个数字,为第一个多项式的系数和指数(幂次数),如3 3代表3*x^3;第三行为2m个数字,为第一个多项式。

    题目OJ数据保证所有的指数从小到大排列,且单个多项式项数不超过100;输出时,要注意控制输出格式。如对于数据:

4
2 2 1
1 1 1 2
1 1 1 2
6 2 0
1 0 1 1 1 2 1 3 1 4 1 5
-1 3 -1 4
0 4 0
0 0 1 1 -1 2 2 3
1 1 0
-1 1
0 0

    输出为:

0

1+x+x^2+x^5

x-x^2+2x^3

-x


>分析

    这个题目麻烦的地方在于考虑输出格式。比较训练对函数模块的抽象能力,好的抽象可以保证不出现一大堆if语句套if语句。

    一个比较关键的点是,当两个多项式的和/差为0时,应当输出0,这是很多代码不被AC的原因。


>代码

#include <iostream>#define addMode 0#define subMode 1#define maxSize 100using namespace std;// 完全没输出(相加相减/为0时) bool outputed = false;int abs(int num){return num>0?num:-1*num;}// 根据计算模式计算系数 : 此题只有两种模式——加或减 int calculate(int a,int b,int mode){if(mode == addMode) return a+b;else return a-b;}// 输出次幂 重点考虑1次幂时不输出 "^幂",0次幂时不输出"x"void outputX(int x){if(x==1) cout<<"x";else if(x>1) cout<<"x^"<<x;}// 输出系数 重点考虑系数为[+-1]时系数省略 (但次数不能为1),为-1时要显示负号 void outputA(int coefficient,int x){if(x==0 || abs(coefficient)!=1) cout << coefficient;if(coefficient == -1) cout<<"-";}// 输出控制 重点考虑首项系数为正时不输出 "+" void outputCtl(int coefficient, int x){if(coefficient==0) return;else if(coefficient > 0 && outputed){cout << "+" ;}outputA(coefficient,x);// 输出系数 outputX(x);// 输出指数 outputed = true;}// 表达式解释器 void expressInterpreter(){int n,m,t;cin>>n>>m>>t;// 解释器开始运作时,没有输出任何字符 outputed = false;// 系数表 int a1[maxSize] = {0}, a2[maxSize] = {0};// 指数表 int x1[maxSize] = {0}, x2[maxSize] = {0};// 表头指针 int top1=0,top2=0;for(int i=0;i<n;i++) cin>>a1[i]>>x1[i];for(int i=0;i<m;i++) cin>>a2[i]>>x2[i];// 扫描表 while(top1<n && top2<m){if(x1[top1] == x2[top2]){int coefficient = calculate(a1[top1],a2[top2],t);if(coefficient!=0) outputCtl(coefficient, x1[top1]);top1++;top2++;} else {if(x1[top1]<x2[top2]){outputCtl(a1[top1], x1[top1]);top1++;} else {outputCtl(a2[top2], x2[top2]);top2++;}}}// 清空残留项 for(;top1<n;top1++)outputCtl(a1[top1], x1[top1]);for(;top2<m;top2++)outputCtl(a2[top2], x2[top2]);// 表达式为0时 直接输出0 if(!outputed) cout<<0<<endl;else cout<<endl;}int main(){int N;cin >> N;for(int i=0;i<N;i++) expressInterpreter();return 0;}


原创粉丝点击