问题 L: 多项式加法

xiaoxiao2021-02-28  65

题目描述 一个多项式可以表示为一组数对,数对中第一个数始终为整数,且唯一,表示多项式的次数,另一数表示为对应的系数且不为0。输入两组数对,每组以0 0作为结束,实现对两个多项式的加法并按降幂输出结果数对 输入 每行输入一个数对,以空格为分隔符,以0 0结束 输出 每行输出一个数对,以空格为分隔符 样例输入 5 12 3 8 1 2 15 5 0 10 0 0 3 12 30 1 15 5 0 0 样例输出 30 1 15 10 5 12 3 20 1 2 0 10

AC代码:

#include <iostream> #include<cstdio> #include<algorithm> using namespace std; struct num{ int x;//指数 int p;//系数 }; bool compare(num a,num b){ if(a.x>b.x) return true; else return false; } int main() { struct num s1[1000]; int _x,_p,_count=0,_x1,_p1; while(scanf("%d%d",&_x1,&_p1)){ if(_x1==0&&_p1==0) break; s1[_count].x=_x1; s1[_count].p=_p1; _count++; } int itemp=_count; while(scanf("%d%d",&_x,&_p)){ if(_x==0&&_p==0) break; int flag=1; for(int k=0;k<itemp;k++){ if(s1[k].x==_x){ s1[k].p+=_p; flag=0; break; } } if(flag){ s1[_count].x=_x; s1[_count].p=_p; _count++; } } sort(s1,s1+_count,compare); for(int i=0;i<_count;i++){ if(s1[i].p==0) continue; //这一步 不同oj可能要求不一样 if(i==_count-1) cout<<s1[i].x<<" "<<s1[i].p; else cout<<s1[i].x<<" "<<s1[i].p<<endl; } return 0; }
转载请注明原文地址: https://www.6miu.com/read-67581.html

最新回复(0)