PAT 甲级 1002 A+B for Polynomials(25)

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 N​1​​ a​N​1​​​​ N​2​​ a​N​2​​​​ ... N​K​​ a​N​K​​​​

where K is the number of nonzero terms in the polynomial, N​i​​ and a​N​i​​​​ (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1 ≤ K ≤ 10,0 ≤ N​​​ < ⋯ < N​2​​ < N​1​​ ≤ 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.

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

Experiential Summing-up

两种办法:

①map(较麻烦):使用三个 map ,键值对为<指数, 系数>,最后利用 vector 进行排序输出。

②array:使用一个数组,将指数相同的系数相加,统计非零系数的个数,最后倒序输出系数不为 0 的指数和系数。

Accepted Code

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 int k, N;
 5 double a;
 6 vector<int> x;
 7 map<int, double> map1, map2, map3;
 8 
 9 int main()
10 {
11     cin >> k;
12     for(int i = 1; i <= k; i ++)
13     {
14         cin >> N >> a;
15         map1[N] = a;
16     }
17     cin >> k;
18     for(int i = 1; i <= k; i ++)
19     {
20         cin >> N >> a;
21         map2[N] = a;
22     }
23     for(int i = 0; i <= 1000; i ++)
24     {
25         if(map1[i] + map2[i] != 0)
26         {
27             x.push_back(i);
28             map3[i] = map1[i] + map2[i];
29         }
30     }
31 
32     sort(x.begin(), x.end());
33     reverse(x.begin(), x.end());
34 
35     cout << x.size();
36     for(int i = 0; i < x.size(); i ++)
37     {
38         cout << " " << x[i] << " ";
39         cout << fixed <<setprecision(1) <<map3[x[i]];
40     }
41     return 0;
42 }

 

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 int n, m, t;
 5 int cnt = 0;
 6 float num;
 7 float c[1001];
 8 
 9 int main()
10 {
11     scanf("%d", &n);
12     for(int i = 0; i < n; i ++)
13     {
14         scanf("%d%f", &t, &num);
15         c[t] += num;
16     }
17     scanf("%d", &m);
18     for(int i = 0; i < m; i ++)
19     {
20         scanf("%d%f", &t, &num);
21         c[t] += num;
22     }
23 
24     for(int i = 0; i < 1001; i ++)
25         if(c[i] != 0) cnt ++;
26     printf("%d", cnt);
27 
28     for(int i = 1000; i >= 0; i --)
29     {
30         if(c[i] != 0.0)
31             printf(" %d %.1f", i, c[i]);
32     }
33     return 0;
34 }

 

posted @ 2023-02-18 19:09  爱吃虾滑  阅读(10)  评论(0编辑  收藏  举报