這仍然是一道關於A/B的題,只不過A和B都換成了多項式。你須要計算兩個多項式相除的商Q和餘R,其中R的階數必須小於B的階數。ios
輸入格式: spa
輸入分兩行,每行給出一個非零多項式,先給出A,再給出B。每行的格式以下:code
N e[1] c[1] ... e[N] c[N]blog
其中N是該多項式非零項的個數,e[i]是第i個非零項的指數,c[i] 是第i個非零項的係數。各項按照指數遞減的順序給出,保證全部指數是各不相同的非負整數,全部係數是非零整數,全部整數在整型範圍內。ci
輸出格式: 數學
分兩行前後輸出商和餘,輸出格式與輸入格式相同,輸出的係數保留小數點後1位。同行數字間以1個空格分隔,行首尾不得有多餘空格。注意:零多項式是一個特殊多項式,對應輸出爲「0 0 0.0」。但非零多項式不能輸出零係數(包括舍入後爲0.0)的項。在樣例中,餘多項式其實有常數項「-1/27」,但因其舍入後爲0.0,故不輸出。io
輸入樣例:4 4 1 2 -3 1 -1 0 -1 3 2 3 1 -2 0 1輸出樣例:
3 2 0.3 1 0.2 0 -1.0 1 1 -3.1
最初看到這道題就頭疼,作加法乘法的時候就很煩心,如今又來個除法,折磨人啊,想了想數學上也作過這種題,拼湊嘛,我記得當時仍是對於分子分母都是多項式的進行化簡的一個方法。。說道拼湊就是a/b,只要a找那個存在比b中最高次的指數大,那麼就能夠拼湊,拿樣例來講,a = x^4 - 3x^2 - x - 1,b = 3x^2 - 2x + 1。對於a的第一項指數4比b最高次指數2大,那麼商的第一項就是x^4/3x^2 = 0.3x^2,而後用0.3x^2去乘以b的每一項,在a中更新,也就是a要減去b*0.3x^2,更新完之後,a要繼續重複以上過程,知道a中最高次比b中最高次低,剩下的就算是餘數了,這裏用了個map記錄a,方便進行更新,b自始至終是不變的。
代碼:
#include <iostream> #include <map> #include <cmath> #include <cstdio> using namespace std;//係數要求保留一位小數,因此絕對值小於0.05都當成0對待 struct poly { int e; double c; }p[10000],ans[10000]; int main() { int n = 0,e = 0,c = 0,m = -1,ant = 0;//m記錄a中最高次 e是指數 c是係數 輸入都是整數 map<int,double> q; cin>>n; for(int i = 0;i < n;i ++) { cin>>e>>c; q[e] = c; if(i == 0)m = e; } cin>>n; for(int i = 0;i < n;i ++) { cin>>p[i].e>>p[i].c; } while(m >= p[0].e) { double change = q[m]/p[0].c;//分析中所述的 a中最高次除以b中最高次 係數比 int diff = m - p[0].e;//指數比 if(fabs(change) >= 0.05) { ans[ant].e = diff; ans[ant ++].c = change; for(int i = 0;i < n;i ++)//change 乘以 b 更新a中的變化 { q[p[i].e + diff] -= change * p[i].c; } } else m --;//必定別忘了m-- 否則會超時,太過於馬虎 if else語句仍是想清楚 寫完備一些好光有if沒else就容易錯誤啊。。 while(m >= p[0].e && fabs(q[m]) < 0.05) { m --; } } cout<<ant; if(!ant)cout<<" 0 0.0"; for(int i = 0;i < ant;i ++) printf(" %d %.1f",ans[i].e,ans[i].c); cout<<endl; ant = 0; while(m >= 0) { if(fabs(q[m]) >= 0.05) { ans[ant].e = m; ans[ant ++].c = q[m]; } m --; } cout<<ant; if(!ant)cout<<" 0 0.0"; for(int i = 0;i < ant;i ++) printf(" %d %.1f",ans[i].e,ans[i].c); }
重溫:class
#include <iostream> #include <cstdio> #include <cstdlib> using namespace std; typedef pair<int,double> pa; pa de[10000],ans[10000]; int n,m,no,e,se; double c,cc[10000]; int main() { cin>>n; if(n) { cin>>e>>c; se = e; cc[e] += c; } for(int i = 1;i < n;i ++) { cin>>e>>c; cc[e] += c; } cin>>m; for(int i = 0;i < m;i ++) { cin>>de[i].first>>de[i].second; } se ++; while(-- se >= de[0].first) { double t = cc[se] / de[0].second; if(t < 0.05 && t > -0.05) continue; ans[no].first = se - de[0].first; ans[no ++].second = t; for(int i = 1;i < m;i ++) { cc[ans[no - 1].first + de[i].first] -= t * de[i].second; } } if(!no) { printf("0 0 0.0"); } else { printf("%d",no); for(int i = 0;i < no;i ++) { printf(" %d %.1f",ans[i].first,ans[i].second); } } int sse = se + 1; for(int i = 0;i <= se;i ++) { if(cc[i] < 0.05 && cc[i] > -0.05) sse --; } printf("\n%d",sse); for(int i = se;i >= 0;i --) { if(cc[i] < 0.05 && cc[i] > -0.05) continue; printf(" %d %.1f",i,cc[i]); } if(!sse) printf(" 0 0.0"); }