This time, you are supposed to find A+B where A and B are two polynomials.
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_{N1} N_2\ a_{N2}...\ N_K\ a_{NK}$
where $K$ is the number of nonzero terms in the polynomial, $N_i$ and $a_{Ni}(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$.
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.
2 1 2.4 0 3.2
2 2 1.5 1 0.5
3 2 1.5 1 2.9 0 3.2
这道题有几个点需要注意:
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 1e3 + 5;
double a[maxn] = {0};
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("input.txt", "r", stdin);
#endif // ONLINE_JUDGE
int k;
cin >> k;
for(int i = 0;i < k;i++){
int exp;
double coe;
cin >> exp >> coe;
a[exp] = coe;
}
cin >> k;
for(int i = 0;i < k;i++){
int exp;
double coe;
cin >> exp >> coe;
a[exp] += coe;
}
int cnt = 0;
for(int i = 0;i < maxn;i++){
if(a[i]){
cnt++;
}
}
printf("%d", cnt);
for(int i = maxn;i >= 0;i--){
//负数也需要输出
if(a[i] != 0){
//cout << " " << i << " " << a[i];
//coe精确到小数点后一位
printf(" %d %.1f", i, a[i]);
}
}
return 0;
}
题目链接:1009 Product of Polynomials
This time, you are supposed to find $A×B$ where $A$ and $B$ are two polynomials.
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_{N1} N_2\ a_{N2}...\ N_K\ a_{NK}$
where $K$ is the number of nonzero terms in the polynomial, $N_i$ and $a_{Ni}(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$.
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.
2 1 2.4 0 3.2
2 2 1.5 1 0.5
3 3 3.6 2 6.0 1 1.6
注意一个坑:作为输出结果的 $C[maxn2]$ 数组,范围需要开到 $2000$ 以上才可。
#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 1005, maxn2 = 2010;
double a[maxn] = {0}, b[maxn] = {0}, c[maxn2] = {0};
int main(){
int k;
cin >> k;
for(int i = 0;i < k;i++){
int exp;
double coe;
cin >> exp >> coe;
a[exp] = coe;
}
cin >> k;
for(int i = 0;i < k;i++){
int exp;
double coe;
cin >> exp >> coe;
b[exp] = coe;
}
for(int i = 0;i < maxn;i++){
for(int j = 0;j < maxn;j++){
c[i + j] += a[i] * b[j];
}
}
int cnt = 0;
for(int i = 0;i < maxn2;i++){
if(c[i]){
cnt++;
}
}
cout << cnt;
for(int i = maxn2;i >= 0;i--){
if(c[i] != 0){
printf(" %d %.1f", i, c[i]);
}
}
return 0;
}