pat甲级1002

1002. A+B for Polynomials (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

主要是细节,要注意有可能相加后某个项会被消掉,这时候总项数要减少,而且为零项不要输出。还有一个效率问题,在读取时就把可能要打印的项数的指数存到一个set(排异性),减少
扫描时间。
 1 #include <iostream>
 2 #include <cstring>
 3 #include <memory>
 4 #include <vector>
 5 #include <algorithm>
 6 #include <cstdio>
 7 #include <set>
 8 
 9 using namespace std;
10 
11 double a[1002];
12 int main(void)
13 {
14   memset(a, 0, sizeof(a));
15   set<int> s;
16 
17   for (int i = 0;i < 2;i++)
18   {
19     int k;
20     cin >> k;
21     for (int j = 0;j < k;j++)
22     {
23       int index;
24       double n;
25       cin >> index >> n;
26       a[index] += n;
27       s.insert(index);//保存
28     }
29   }
30   
31   
32   vector<int> v;
33   v.assign(s.begin(), s.end());//用set构造
34 
35   int cnt = 0;
36   for (int i = v.size();i > 0;--i)
37     if (a[v[i - 1]] != 0.0)cnt++;//判断剩下的k
38   cout << cnt;
39   for (int i = v.size();i > 0;--i)
40     if (a[v[i - 1]] != 0.0)//这里也要判断--
41       printf(" %d %.1lf", v[i - 1], a[v[i - 1]]);
42   printf("\n");
43 
44   return 0;
45 }

 

posted on 2018-04-10 14:53  只是个回忆录  阅读(90)  评论(0编辑  收藏  举报

导航