CCCC L2-018. 多项式A除以B 直接上map,然后stack处理输出

https://www.patest.cn/contests/gplt/L2-018

题意:模拟多项式除法。

题解:短除法,初中奥数老师,高中数学老师,高数老师都讲过2333。

   模拟之前,关于保存 多项式的方法。考虑到系数可能很分散(1~1e9),直接用map存(map基本就是为多项式加减法定制的)

    模拟的时候,就是数学课上短除法的算法,注意一下循环终止条件及其控制:当多项式A的最高次系数小于B的时,除不下去,此时A已然为余数。

    模拟完,输出 。本来用stack只是因为auto:t不能逆向输出,结果顺便把四舍五入及删零操作顺便解决了(不理解的地方是floor(x+0.5)对负数(-0.5)为什么也能四舍五入,貌似数据太弱)。

    最后,记得判掉零项

坑:题目没看清,没有特判掉零多项式,然后在那里XJBL改。//改了负数的四舍五入,改了一下及时erase掉系数为0的项,显然并卵。无奈搜了一下题解,ac代码赫然多了一行 “0 0 0”   0_0!


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>
#include <cstring>
#include <string>
#include <map>
#include<stack>
#include<set>
#include<string.h>
#include<list>
#define pb push_back
#define mp make_pair
#define _for(i, a, b) for (int i = (a); i<(b); ++i)
#define _rep(i, a, b) for (int i = (a); i <= (b); ++i)


using namespace std;
typedef long long ll;
const int N = 1e5 + 5;
int len;
map<int, float> a, b, c, d;


int main() {
int n; cin >> n;
_for(i, 0, n) {
int x, y;
cin >> x >> y;
a[x] = y;
}
cin >> n;
_for(i, 0, n) {
int x, y;
cin >> x >> y;
b[x] = y;
}

//模拟短除法:
while (a.rbegin()->first >= b.rbegin()->first) {
int e = a.rbegin()->first - b.rbegin()->first;
float f = a.rbegin()->second / b.rbegin()->second;
c[e] += f;
for (auto t : b) {
a[t.first + e] -= f*t.second;
}
if (a.rbegin()->second == 0) a.erase(a.rbegin()->first);


}
//反向输出,四舍五入判定
stack<pair<int, float> > ta, tb;
for (auto t : c) {
float temp = t.second * 10;
temp = floor(temp + 0.5);
if (temp == 0) continue;
else {
temp /= 10;
ta.push(mp(t.first, temp));
}
}
for (auto t : a) {
float temp = t.second * 10;
temp = floor(temp + 0.5);
if (temp == 0) continue;
else {
temp /= 10;
tb.push(mp(t.first, temp));
}
}
cout << ta.size(); if (ta.size() == 0) { cout << " 0 0.0"; }else while (!ta.empty()) { cout << ' ' << ta.top().first << ' '; printf("%.1lf", ta.top().second); ta.pop(); }
cout << endl;
cout << tb.size(); if (tb.size() == 0) {cout << " 0 0.0" ;}else while (!tb.empty()) { cout << ' ' << tb.top().first << ' '; printf("%.1lf", tb.top().second); tb.pop(); }


system("pause");
}
/*1 2 3*/

 
成功的路并不拥挤,因为大部分人都在颓(笑)
原文地址:https://www.cnblogs.com/SuuT/p/8672270.html