1002 A+B for Polynomials (25 分)

This time, you are supposed to find  where  and  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:

       

where  is the number of nonzero terms in the polynomial,  and  () are the exponents and coefficients, respectively. It is given that .

Output Specification:

For each test case you should output the sum of  and  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

题目解读:输入A、B两个多项式数列,求这两个多项式的和以及有效项个数,保留一位小数。

解题思路: 因为最大指数不是很大,所以直接用数组储存这两个多项式,不需要分别放两个,放在一个里面加就可以了,数组最好用fill()初始化一下。速度还是有点慢,卡在了输出格式上,题目的保留一位小数用%.1f输出就可以了,我用了%g输出,区别就是%g保留的是有效数字。还在最后一个格式卡了一下,如果是答案是0的话就没有后面一个空格,所以空格应该是每输出一组多项式之前带的,改了一下就通过了。

AC代码

#include <iostream>
#include <vector>
using namespace std;
struct node{
    int a;
    float b;
    node(int n1,float n2){
        a = n1;
        b = n2;
    }
};
vector<node> result;
float ans[1003];
int main(int argc, const char * argv[]) {
    int n;
    fill(ans,ans+1003,0);
    for( int num = 0 ; num < 2 ; num ++ ){
    scanf("%d",&n);
    for( int i = 0; i < n ; i ++ ){
        int t;
        float p;
        scanf("%d %f",&t,&p);
        ans[t] = ans[t]+p;
    }
    }
    for(int i = 1002 ; i >= 0 ; i -- ){
        if(ans[i] != 0 ){
            result.push_back(node(i,ans[i]));
        }
    }
    printf("%d",result.size());
    for( int i = 0 ; i < result.size(); i ++ ){
        printf(" %d %.1f",result[i].a,result[i].b);
    }
    return 0;
}

 

 


0 条评论

发表评论

Avatar placeholder