这道题的题目链接:http://pat.zju.edu.cn/contests/pat-practise/1002
题目很简单,就是模拟两个多项式的和,指数相同则系数相加,最后将结果按输入时的格式输出,输出时应该按照指数递减排序,而且,这道题后面3个案例有陷阱:不要输出系数为0的项,计算项数总数目的时候也不要计算这些系数为0的项,如果A和B中某个指数项的相应系数均不为0,当然要相加,但不要马上存入结果多项式中,应该判断此时的系数和是否为0,如果不为0,再存结果;否则,这一项忽略掉,不要存储,也不要使总数目加1,这个小细节让我WA了2次。
1 #include <stdio.h>
2
3 typedef struct
4 {
5 int ni;//指数
6 double ani;//系数
7 }poly;
8
9 int main()
10 {
11 int k1,k2;
12 poly a[12], b[12], c[30];
13 int i,j,pos;
14 int t1;
15 double t2;
16 while(scanf("%d", &k1) != EOF)
17 {
18 for(i = 0; i < k1; i ++)
19 {
20 scanf("%d %lf", &a[i].ni, &a[i].ani);
21 }
22 scanf("%d", &k2);
23 for(i = 0; i < k2; i ++)
24 {
25 scanf("%d %lf", &b[i].ni, &b[i].ani);
26 }
27 pos = 0;
28 for(i = 0, j = 0; i < k1 && j < k2;)
29 {
30 if(a[i].ni == b[j].ni)
31 {
32 t1 = a[i].ni;
33 t2 = a[i].ani + b[j].ani;
34 if(t2 != 0)
35 {
36 c[pos].ni = t1;
37 c[pos].ani = t2;
38 pos ++;
39 i ++;
40 j ++;
41 }
42 else
43 {
44 i ++;
45 j ++;
46 }
47 }
48 else if(a[i].ni > b[j].ni)
49 {
50 t1 = a[i].ni;
51 t2 = a[i].ani;
52 if(t2 != 0)
53 {
54 c[pos].ni = t1;
55 c[pos].ani = t2;
56 pos ++;
57 i ++;
58 }
59 else
60 {
61 i ++;
62 }
63 }
64 else
65 {
66 t1 = b[j].ni;
67 t2 = b[j].ani;
68 if(t2 != 0)
69 {
70 c[pos].ni = t1;
71 c[pos].ani = t2;
72 pos ++;
73 j ++;
74 }
75 else
76 {
77 j ++;
78 }
79 }
80 }
81 if(i < k1)
82 {
83 for(; i < k1; i ++)
84 {
85 t1 = a[i].ni;
86 t2 = a[i].ani;
87 if(t2 != 0)
88 {
89 c[pos].ni = t1;
90 c[pos].ani = t2;
91 pos ++;
92 }
93 }
94 }
95 if(j < k2)
96 {
97 for(; j < k2; j ++)
98 {
99 t1 = b[j].ni;
100 t2 = b[j].ani;
101 if(t2 != 0)
102 {
103 c[pos].ni = b[j].ni;
104 c[pos].ani = b[j].ani;
105 pos ++;
106 }
107 }
108 }
109 printf("%d", pos);
110 for(i = 0; i < pos; i ++)
111 {
112 printf(" %d %.1lf",c[i].ni, c[i].ani);
113 }
114 printf("\n");
115 }
116 return 0;
117 }