1002 A+B for Polynomials

This time, you are supposed to find A+B where A and B are two polynomials.

这次,你需要找到两个多项式AB的和。

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_{N1} N_2 a_{N2} ... N_{K} a_{NK}

where K is the number of nonzero terms in the polynomial, N_{i} and a_{Ki} (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10 0≤N_{K}<⋯<N_{2}<N_{1}≤1000

每个输入文件包含一个测试用例。每个测试用例占2行,每行包含一个多项式的信息:

K N_1 a_{N1} N_2 a_{N2} ... N_{K} a_{NK}

其中K是多项式中非零项的数量,N_{i}a_{Ki}i=1,2,⋯,K)分别是指数和系数。给定 1≤K≤10 0≤N_{K}<⋯<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.

对于每个测试用例,你应该在一行中输出AB的和,输出格式与输入格式相同。注意:每行末尾不能有多余的空格。请保留1位小数。

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

题目解释

直接上样例:

2 1 2.4 0 3.2

表示多项式a含有两个非零项 2.4x^1+3.2x^0

同理

2 2 1.5 1 0.5

表示多项式b含有两个非零项 1.5x^2+0.5x^1

求a+b的结果

3 2 1.5 1 2.9 0 3.2

1.5x^2+2.9x^1+3.2

我的思路

#include<bits/stdc++.h>
using namespace std;
int main(){
	//使用map去重并排序 
	map<int,float,greater<int>> m;
	int size;
	for(int j=0;j<2;j++){
		cin>>size;
		for(int i=0;i<size;i++){
			int n;
			float a;
			cin>>n>>a;
			if(m[n])m[n]+=a;
			else m[n]=a;
		}
	}
	cout<<m.size();
	for(auto x:m){
		print(" %d %.1f",x.first,x.second);
	}
}

得分:17

这里有个坑,输入的多项式中系数可以为0,但输出的多项式中系数不能为0,得手动去除。

#include<bits/stdc++.h>
using namespace std;
int main(){
	//使用map去重并排序 
	map<int,float,greater<int>> m;
	int size;
	for(int j=0;j<2;j++){
		cin>>size;
		for(int i=0;i<size;i++){
			int n;
			float a;
			cin>>n>>a;
			if(m[n])m[n]+=a;
			else m[n]=a;
		}
	}
    int cnt=0;
    for(auto x:m){
        if(x.second!=0.0) cnt++;
	}
    cout<<cnt;
	for(auto x:m){
        if(x.second!=0.0) printf(" %d %.1f",x.first,x.second);
	}
}

得分25

Solution

#include <iostream>
using namespace std;
int main() {
    float c[1001] = {0};
    int m, n, t;
    float num;
    scanf("%d", &m);
    for (int i = 0; i < m; i++) {
        scanf("%d%f", &t, &num);
        c[t] += num;
    }
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d%f", &t, &num);
        c[t] += num;
    }
    int cnt = 0;
    for (int i = 0; i < 1001; i++) {
        if (c[i] != 0) cnt++;
    }
    printf("%d", cnt);
    for (int i = 1000; i >= 0; i--) {
        if (c[i] != 0.0)
            printf(" %d %.1f", i, c[i]);
    }
    return 0;
}

思路几乎一致,即输入、有序数组,相加输出。

经验:可以通过比题目规定范围稍大的数组代替map,空间复杂度降低。


标题:PAT 1002 两多项式相加
作者:Departure
地址:https://www.unreachablecity.club/articles/2023/04/15/1681568490767.html