PTA 甲级 A+B for Polynomials

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000
在这里插入图片描述
多项式相加,本意考察链表,可用数组偷懒

第一种做法卡了一个点,不过我也大致知道卡在那里了,但是想出更好的解决办法就没有改进

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;
const int N = 1010;

struct node
{
	int x;
	double z;
};

bool cmp(node &a, node &b)
{
	return a.x > b.x;
}

vector<node> f1, f2, res;

int main()
{
	int K;cin >> K;
	node y; 
	while(K--) 
	{
		cin >> y.x >> y.z;
		f1.push_back(y);
	}
	cin >> K;
	while(K--)
	{
		cin >> y.x >> y.z;
		f2.push_back(y);
	}
	
	sort(f1.begin(), f1.end(), cmp);
	sort(f2.begin(), f2.end(), cmp);
	
	int a = 0,b = 0;
	for(int i = 0; i <= max(f1.size(), f2.size()); i ++ )
	{
		if(a == f1.size()) 
		{
			if(b<f2.size()) res.push_back(f2[b]), b++;
			continue;
		}
		if(b == f2.size())
		{
			if(a<f1.size()) res.push_back(f1[a]), a++;
			continue;
		}
		if(f1[a].x>f2[b].x) res.push_back(f1[a]), a++;
		else if(f1[a].x==f2[b].x)
		{
			node tmp;
			tmp.x = f1[a].x;
			tmp.z = f1[a].z+f2[b].z;
			if(tmp.z!=0) res.push_back(tmp);
			a++,b++;
		}
		else res.push_back(f2[b]), b++;
	}
	if(res.size() == 0)
	{
		cout<<"0";return 0;
	} 
	sort(res.begin(), res.end(), cmp);
	
	cout << res.size()<<" ";
	
	
	for(int i = 0; i < res.size(); i ++ )
	{
		if(i == 0) printf("%d %.1lf",res[i].x,res[i].z);
		else printf(" %d %.1lf",res[i].x,res[i].z);
	}
	return 0;
}

代码写的很臭,总结了几个坑点

  • 相抵消的情况,比如
1 0 -1
1 0 1 

output

0
  • 它的输入并不一定是合并完的多相式
2 2 0.2 2 -0.1
3 3 7.8 2 6 1 9

output

3 3 7.8 2 6.1 1 9.0

第一个代码应该是卡在了第二个坑点
在这里插入图片描述
ac代码:

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
const int N = 1010;

double f[N];

int main()
{
	int cnt = -1;
	for(int j = 0; j < 2; j ++ ) 
	{
		int k; cin >> k;
		int x;
		double y;
		for(int i = 0; i < k; i ++ )
		{
			cin >> x >> y;
			f[x] += y;
			cnt = max(cnt, x);
		}
	}
	int res = 0;
	for(int i = 0; i <= cnt; i ++ )
		if(f[i]!=0) res++;
	
	cout << res;
	for(int i = cnt; i >= 0; i -- )
		if(f[i]!=0) printf(" %d %.1lf",i,f[i]);
	
	return 0;
}

欢迎大家指正~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1bu3dong

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值