zoukankan      html  css  js  c++  java
  • 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("
    ");
    43 
    44   return 0;
    45 }
  • 相关阅读:
    Java数据持久层
    一张图解决ThreadLocal
    类加载器及其加载原理
    手写LRU缓存淘汰算法
    使用归并排序思想解决逆序对数量问题
    Same Origin Policy 浏览器同源策略详解
    如何估算线程池的线程数?
    分布式锁为什么要选择Zookeeper而不是Redis?
    SpringBoot的SpringMVC使用FastJson依赖时LocalDateTime全局配置序列化格式
    数据库中的枚举值如何存储
  • 原文地址:https://www.cnblogs.com/schsb/p/8779042.html
Copyright © 2011-2022 走看看