PAT A1002 A+B for Polynomials

PAT A1002 A+B for Polynomials

在这里插入图片描述

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
wordmeaning
polynomialsn. 多项式
nonzero terms非零项
exponentn.指数
coefficientn. 系数
decimal place小数位
  • 思路1:
    用一个数组,下标i表示多项式对应指数项,循环输入两次,累加每一项的系数,最后遍历数组,就得到了结果

  • code1:

#include <stdio.h>
#include <cstring>
const int maxn = 1111;
double ans[maxn];
int main(){
	int n, e, cnt = 0;
	double c;
	memset(ans, 0, sizeof(ans));
	for(int i = 0; i < 2; ++i){
		scanf("%d", &n);
		for(int j = 0; j < n; ++j){
			scanf("%d %lf", &e, &c);
			ans[e] += c;
		}
	}
	for(int i = 0; i < maxn; ++i){
		if(ans[i] != 0) cnt++;
	}
	printf("%d", cnt);
	for(int i = maxn-1; i >= 0; --i){
	//!!!:又忘了-- 
		if(ans[i] != 0){
			printf(" %d %.1lf", i, ans[i]);		//!!!:主要输出格式 
//			if(i != 0) printf(" "); 	//这个条件不对,有可能最后一位不是0
		}
	}
}
  • code:Map实现
#include <bits/stdc++.h>
using namespace std;
map<int, double> poly;
int main(){
	int n, ex;
	double co;
	scanf("%d", &n);
	for(int i = 0; i < n; ++i){
		scanf("%d %lf", &ex, &co);
		poly[ex] = co;
	}
	scanf("%d", &n);
	for(int i = 0; i < n; ++i){
		scanf("%d %lf", &ex, &co);
		poly[ex] += co; 
		if(poly[ex] == 0) poly.erase(ex); //Wrong 1:要将系数和为0的项消去(样例3~6) 
	}
	printf("%d", poly.size());
	for(auto it = poly.rbegin(); it != poly.rend(); ++it){
		printf(" %d %.1f", it->first, it->second);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值