博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PAT 1002. A+B for Polynomials
阅读量:4512 次
发布时间:2019-06-08

本文共 3000 字,大约阅读时间需要 10 分钟。

PAT 1002. A+B for Polynomials

This time, you are supposed to find A+B where A and B are two polynomials.

Input

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial: K N1 aN1 N2 aN2 ... NK aNK, where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1, 2, ..., K) are the exponents and coefficients, respectively. It is given that 1 <= K <= 10,0 <= NK < ... < N2 < N1 <=1000.

Output

For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.

Sample Input

2 1 2.4 0 3.22 2 1.5 1 0.5

Sample Output

3 2 1.5 1 2.9 0 3.2

代码如下(复杂的链表)

#include
using namespace std;struct node{ int exp; double coe; node* next;};int main(){ int N,cnt=0; cin>>N; node* l1=new node(); node* ptr1=l1; for(int i=0;i
next=NULL; cin>>lnode->exp>>lnode->coe; ptr1->next=lnode; ptr1=ptr1->next; } cin>>N; node* l2=new node(); node* ptr2=l2; for(int i=0;i
>lnode->exp>>lnode->coe; lnode->next=NULL; ptr2->next=lnode; ptr2=ptr2->next; } ptr1=l1->next; ptr2=l2->next; node* l=new node(); node* ptr=l; while(ptr1!=NULL&&ptr2!=NULL){ if(ptr1->exp>ptr2->exp){ if(ptr1->coe!=0) cnt++; ptr->next=ptr1; ptr=ptr->next; ptr1=ptr1->next; } else if(ptr1->exp
exp){ if(ptr2->coe!=0) cnt++; ptr->next=ptr2; ptr=ptr->next; ptr2=ptr2->next; }else{ ptr1->coe+=ptr2->coe; if(ptr1->coe!=0) cnt++; ptr->next=ptr1; ptr=ptr->next; ptr1=ptr1->next; ptr2=ptr2->next; } } while(ptr1!=NULL){ if(ptr1->coe!=0) cnt++; ptr->next=ptr1; ptr=ptr->next; ptr1=ptr1->next; } while(ptr2!=NULL){ if(ptr2->coe!=0) cnt++; ptr->next=ptr2; ptr=ptr->next; ptr2=ptr2->next; } ptr=l->next; cout<
coe!=0) printf(" %d %.1f",ptr->exp,ptr->coe); ptr=ptr->next; }}

分析

其实用其他容器都可以很好的解决这个问题,vector,map等等;下面附上我的另一种解法

代码如下

#include
#include
using namespace std;int main(){ map
map1,map2; int N,exp,cnt=0; double coe; cin>>N; for(int i=0;i
>exp>>coe; map1[exp]=coe; } cin>>N; for(int i=0;i
>exp>>coe; map2[exp]=coe; } auto p1=map1.begin(); for(;p1!=map1.end();p1++){ map2[p1->first]+=p1->second; } for(auto p2=map2.rbegin();p2!=map2.rend();p2++){ if(p2->second!=0) cnt++; } cout<
second!=0) printf(" %d %.1f",p2->first,p2->second); }}

转载于:https://www.cnblogs.com/A-Little-Nut/p/8175953.html

你可能感兴趣的文章
APP压力稳定性测试
查看>>
Windows文件操作基础代码
查看>>
1-8
查看>>
阶段1 语言基础+高级_1-3-Java语言高级_04-集合_04 数据结构_2_数据结构_队列
查看>>
Entity Framework操作Oracle数据库实现主键自增问题
查看>>
Leetcode WC-108-03 931-下降路径最小和
查看>>
从“智猪博弈”看所谓“大国责任”
查看>>
Day3:Spring-JDBC、事务管理
查看>>
模块的四种形式
查看>>
教你如何培养幽默感
查看>>
asp.net的一个简单简历缓存方法
查看>>
loj 1185(bfs)
查看>>
全排列-按从大到小-time limited
查看>>
减肥中,做个 体重三围 测量软件
查看>>
windows下命令行修改系统时间;修改系统时间的软件
查看>>
[LeetCode] 384. Shuffle an Array 数组洗牌
查看>>
最大公约数
查看>>
序列化和反序列化
查看>>
Mac上Chrome浏览器跨域解决方案
查看>>
Sublime Text 3 全程详细图文原创教程(持续更新中。。。)
查看>>