L2-018 多项式A除以B(模拟)

题目连接

https://pintia.cn/problem-sets/994805046380707840/problems/994805060372905984

思路

其实就是一个多项式的除法运算,我们尽可能将 B B B 的最大项凑到和 A的对应位置项同阶,然后做一个减法运算即可,详情请参考代码,注意的是这里有几个坑点:

  • 余数的阶数小于商的阶数:测试点3、4
  • 去除商中的零项:测试点1、4
  • B的最大阶比A大:测试点2、3

代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
#define INF 0x3f3f3f3f

const int N = 2e4 + 10;

double a[N], b[N], q[N];

struct Node {
    
    
	int e;
	double c;
};

void print(vector<Node> &ans) {
    
    
	int l = ans.size();
	cout << l << " ";
	for (int i = 0; i < l; ++i) {
    
    
		cout << ans[i].e << " " << ans[i].c << " \n"[i == l - 1];
	}
	if (!l) cout << "0 0.0" << endl;
}

int n, m;
int main() {
    
    
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cout << fixed << setprecision(1);
	cin >> n;
	double ci;
	int ei, maxe1 = 0, maxe2 = 0;
	for (int i = 1; i <= n; ++i) {
    
    
		cin >> ei >> ci;
		a[ei] = ci;
		maxe1 = max(maxe1, ei);
	}
	cin >> m;
	for (int i = 1; i <= m; ++i) {
    
    
		cin >> ei >> ci;
		b[ei] = ci;
		maxe2 = max(maxe2, ei);
	}
	//除法运算
	for (int i = maxe1; i >= maxe2; --i) {
    
    
		int qe = i - maxe2;
		double qc = a[i] / b[maxe2];
		q[qe] = qc;
		for (int j = maxe2; j >= 0; --j) {
    
    
			int pe = j + qe;
			double pc = qc * b[j];
			a[pe] -= pc;
		}
		a[i] = 0;
	}
	//得到商
	vector<Node> ans;
	for (int i = maxe1 - maxe2; i >= 0; --i)
		if (fabs(q[i]) >= 0.05)
			ans.push_back({
    
    i, q[i]});
	
	print(ans);
	//得到余数
	ans.clear();
	for (int i = maxe1; i >= 0; --i)
		if (fabs(a[i]) >= 0.05)
			ans.push_back({
    
    i, a[i]});
	
	print(ans);
	return 0;
}
/*
2 4 4 3 2
2 5 4 3 2

*/

猜你喜欢

转载自blog.csdn.net/m0_46201544/article/details/123972360
今日推荐