相同次数的系数合并,统计系数不为0的项,输出。
a[exp] += num; 比如a[2]也就是x的平方的系数。exp = 0也就是常数项。
因为没有说同一行输入不会出现相同次数的项,因此要+=,当然+=也能很好地处理系数不同的问题。
求8x²-7x+5与3x²-4x+1的差。
解: (8x²-7x+5)-(3x²-4x+1)
=8x²-7x+5-3x²+4x-1
=5x²-3x+41
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using namespace std;
int main() {
int k1, k2, exp;
float num, a[1001] = {0.0};
scanf("%d", &k1);
while (k1--) {
scanf("%d%f", &exp, &num);
a[exp] += num;
}
scanf("%d", &k2);
while (k2--) {
scanf("%d%f", &exp, &num);
a[exp] += num;
}
int cnt = 0;
for (int i = 1000; i >= 0; i--) {
if (a[i]) cnt++;
}
printf("%d", cnt);
for (int i = 1000; i >= 0; i--) {
if (a[i])
printf(" %d %.1f", i, a[i]);
}
return 0;
}
2 1 2.4 0 3.2
2 2 1.5 1 0.5
3 2 1.5 1 2.9 0 3.2