题目链接:(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 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 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;
}