这题我自己写的,但是又臭又长.
贴一下,自己的代码,毕竟是自己写的.
原题如下
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.2
2 2 1.5 1 0.5
Sample Output
3 2 1.5 1 2.9 0 3.2
题目意思:计算多项式A+B的和
分析如下:
用两个数组,a,b分别用来保存多项式a,b。然后在用一个数组c来保存他们相加的结果。
a[偶数]表示的是指数,a[奇数]表示的是系数.b也是同理
例子如下:
a[0]=1;
a[1]=2.2;
这个多项式的系数是2.2,指数是1
题目中要注意的点。
一:他们相加消掉莫一项的情况
二:他们相加最后结果为0的情况
我的代码如下
#include<iostream>
using namespace std;
int main() {
double a[30], b[30], c[50];
int number_a, number_b, number_c = 0,N_a = 0, N_b = 0, N_c = 0;
cin >> number_a; //输入a的个数
for (int i = 0; i < number_a * 2; i = i + 2) {
cin >> a[i] >> a[i + 1];
}
cin >> number_b; //输入b的个数
for (int i = 0; i < number_b * 2; i = i + 2) {
cin >> b[i] >> b[i + 1];
}
while (N_a < 2*number_a && N_b < 2*number_b) { //一旦有一个数组用完就弹出
if (a[N_a] == b[N_b]) { //a和b的指数相等的情况下
if ((a[N_a + 1] + b[N_b + 1]) != 0) { //系数不能消掉的情况下
c[N_c] = a[N_a];
c[N_c + 1] = a[N_a + 1] + b[N_b + 1];
N_a = N_a + 2;
N_b = N_b + 2;
N_c = N_c + 2;
number_c++;
}
else //系数消掉的情况下
{
N_a = N_a + 2;
N_b = N_b + 2;
}
}
else if (a[N_a] > b[N_b]) { //a的系数比b的大
c[N_c] = a[N_a];
c[N_c + 1] = a[N_a + 1];
N_a = N_a + 2;
N_c = N_c + 2;
number_c++;
}
else if (a[N_a] < b[N_b]) { //b的比a大
c[N_c] = b[N_b];
c[N_c + 1] = b[N_b + 1];
N_b = N_b + 2;
N_c = N_c + 2;
number_c++;
}
}
while (N_a < 2*number_a) { //a中还有没有比完的
c[N_c] = a[N_a];
c[N_c + 1] = a[N_a + 1];
N_a = N_a + 2;
N_c = N_c + 2;
number_c++;
}
while (N_b < 2*number_b) { //b中还有没有比完的
c[N_c] = b[N_b];
c[N_c + 1] = b[N_b + 1];
N_b = N_b + 2;
N_c = N_c + 2;
number_c++;
}
int i=0;
if (i >= N_c - 2 && c[i + 1] == 0) { //结果为空的情况下
printf("0");
return 0;
}
cout << number_c << " ";
for (i = 0; i < N_c - 2; i=i+2) {
printf("%0.0f %0.1f ",c[i], c[i + 1]);
}
printf("%0.0f %0.1f", c[i], c[i + 1]); //最后的格式调整
}
下面请和我一起欣赏柳婼大神的代码
#include <iostream>
#include<stdio.h>
using namespace std;
int main() {
float c[1001] = { 0 }; //1001是因为数组的下标就是指数
//数组的值就是系数,这样相加起来就很方便
int m, n, t;
float num;
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d%f", &t, &num);
c[t] += num;
}
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%f", &t, &num);
c[t] += num;
}
int cnt = 0; //计算多项式里面项式的个数
for (int i = 0; i < 1001; i++) {
if (c[i] != 0) cnt++;
}
printf("%d", cnt); //输出个数
for (int i = 1000; i >= 0; i--) {
if (c[i] != 0.0) //只有不为0的时候,输出
printf(" %d %.1f", i, c[i]); //空格写在前面就不需要像我一样在写一个判断语句
}
return 0;
}