题目 A+B for Polynomials
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.
解析
两个多项式,K为各多项式的不为0的项式和。求两个多项式和
注意:
- 两数相加为0,最后结果不输出
- 最后结果必须为小数点后1位
源码
https://github.com/vlluvia/pat
代码
旧代码
#include <iostream>
#include<iomanip>
using namespace std;
void pat1002() {
int k1, k2;
int n1[15],n2[15],n3[35];
float an1[1005],an2[1005],an3[3005];
int n3m = 0;
int n1i = 0, n2j = 0;
cin >> k1;
for (int i = 0; i < k1; ++i) {
cin >> n1[i];
cin >> an1[n1[i]];
}
cin >> k2;
for (int i = 0; i < k2; ++i) {
cin >> n2[i];
cin >> an2[n2[i]];
}
while (n1i != k1 && n2j != k2) {
if (n1[n1i] > n2[n2j]) {
n3[n3m] = n1[n1i];
an3[n3[n3m]] = an1[n1[n1i]];
++n3m; n1i++;
continue;
}
if (n1[n1i] == n2[n2j]) {
if (an1[n1[n1i]] + an2[n2[n2j]] != 0){
n3[n3m] = n1[n1i];
an3[n3[n3m]] = an1[n1[n1i]] + an2[n2[n2j]];
++n3m;
}
++n1i;++n2j;
continue;
}
if (n1[n1i] < n2[n2j]) {
n3[n3m] = n2[n2j];
an3[n3[n3m]] = an2[n2[n2j]];
++n3m; ++n2j;
}
}
if (n1i != k1) {
for (int i = n1i; i < k1; ++i) {
n3[n3m] = n1[i];
an3[n3[n3m]] = an1[n1[i]];
++n3m;
}
} else {
for (int i = n2j; i < k2; ++i) {
n3[n3m] = n2[i];
an3[n3[n3m]] = an2[n2[i]];
++n3m;
}
}
cout << n3m ;
for (int k = 0; k < n3m; ++k) {
printf(" %d %.1lf",n3[k],an3[n3[k]] );
}
}
int main() {
pat1002();
return 0;
}
新代码
#include<bits/stdc++.h>
#define INF 1<<30
using namespace std;
double data[1001] = {0};
int sum = 0;
int t, nk;
double ank;
void pat1002() {
fill(data, data+1000, 0);
for (int i = 0; i < 2; ++i) {
cin >> t;
for (int j = 0; j < t; ++j) {
cin >> nk >> ank;
if(data[nk] == 0)
sum++;
data[nk] += ank;
if(data[nk] == 0)
sum--;
}
}
printf("%d", sum);
for (int j = 1000; j >= 0; --j) {
if(data[j] != 0){
printf(" %d %.1lf", j, data[j]);
}
}
}
int main() {
pat1002();
return 0;
}