PAT甲级 - 1002 A+B for Polynomials (25 分)

题目链接:(PAT甲级)1002 A+B for Polynomials (25 分)

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

Input Specification:

Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:

K N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ ... N​K​​ a​N​K​​​​

where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N​K​​<⋯<N​2​​<N​1​​≤1000.

Output Specification:

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.2
2 2 1.5 1 0.5

Sample Output:

3 2 1.5 1 2.9 0 3.2

题解:看到这题,就想起之前做的一道链表题:给你两条有序的链表将其合并成一条有序的链表。同样的思路进行模拟,令我感到困惑的是,总是有几个测试点过不了。。。

  

最后发现,题目中给出了多项式的指数和系数,当系数为0的时候,这一项就相当于没有了,不要再算一项了。

仔细想想很亏啊,就差一行代码,就能拿到剩下的8分了(ps.学好英语很重要啊,如果读题的时候就能认识指数和系数,,,可惜没有如果)

AC的代码:

#include <iostream>
#include <cstdio>
#include<cmath>
using namespace std;

struct Node{
	int n;
	double a;
}me[15],ms[15],ans[30];

int main(){
	int k1,k2;
	while(~scanf("%d",&k1)){
	  for(int i=0;i<k1;i++){
  		scanf("%d%lf",&me[i].n,&me[i].a);
  	}
  	scanf("%d",&k2);
  	for(int i=0;i<k2;i++){
  		scanf("%d%lf",&ms[i].n,&ms[i].a);
  	}
  	int r=0,r1=0,r2=0;
  	while(r1<k1&&r2<k2){
  		if(me[r1].n==ms[r2].n){
  			ans[r].n=me[r1].n;
  			ans[r].a=me[r1].a+ms[r2].a;
  			if(ans[r].a!=0) r++;   //8分的代码
  			r1++;
  			r2++;
  		}else if(me[r1].n>ms[r2].n){
  			ans[r].n=me[r1].n;
  			ans[r++].a=me[r1].a;
  			r1++;
  		}else{
  			ans[r].n=ms[r2].n;
  			ans[r++].a=ms[r2].a;
  			r2++;
  		}
  	}
  	while(r1<k1){
  		ans[r].n=me[r1].n;
  		ans[r++].a=me[r1].a;
  		r1++;
  	}
  	while(r2<k2){
  		ans[r].n=ms[r2].n;
  		ans[r++].a=ms[r2].a;
  		r2++;
  	}
  	printf("%d",r);
  	for(int i=0;i<r;i++){
  		printf(" %d %.1f",ans[i].n,ans[i].a);
  	}
  	printf("\n");
	}
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值