NC16622多項(xiàng)式輸出【題解】【入門向】

這道題在做的時(shí)候給自己挖了個(gè)坑,其實(shí)把符號(hào)、系數(shù)、指數(shù)分開來看會(huì)更好實(shí)現(xiàn)。
這里先給出不斷調(diào)試給出的答案,思路不是一蹴而就的。
一
輸入:
5
100 -1 1 -3 0 10
輸出:
100x^5-x^4+x^3-3x^2+10
二
輸入:
3
輸出:
-50 0 0 1
-50x^3+1
首先看到示例。這樣的示例是不夠的,因?yàn)橹笖?shù)為1的時(shí)候x后面是不帶“^”的,但是此處并未給出指數(shù)為1時(shí)的示例,因此可以自己給出一個(gè)綜合性比較強(qiáng)的調(diào)試示例
三
輸入:
5
0 -1 1 10 0 1 -1
輸出:
-x^4+x^3+10x^2+1
開始o(jì)ur 工程!
#include<bits/stdc++.h>
using namespace std;
int main()
{
? ?int n;
? ?cin>>n;
? ?int cnt=n;
? ?int a[10000];
首先進(jìn)行輸入的讀取,存到n,由于這個(gè)n是題目給出的常量,最好不要?jiǎng)?,所以我們用cnt來作為變量暫時(shí)存儲(chǔ)n,以備不時(shí)之需。另外根據(jù)示例,我們需要輸入n+1個(gè)指數(shù),因此用數(shù)組來存儲(chǔ)。
int i=0;
? ?cnt++;
? ?while(cnt--)
? ?{
? ? ? ?cin>>a[i];
? ? ? ?i++;
? ?}
此處使用了一個(gè)簡單的while循環(huán)來輸入存儲(chǔ)數(shù)組,cnt充當(dāng)計(jì)數(shù)君,不要忘記有n+1個(gè)數(shù)據(jù)所以要先cnt++
? ?cnt=n;
? ?int meiyoufuhao=0;
? ?for(i=0;i<=n;i++)
? ?{
? ? ? ?if(a[i]!=0)
? ? ? ?{
? ? ? ? ? ?meiyoufuhao=i;
? ? ? ? ? ?break;
? ? ? ?}
? ?}
? ?
? ?for(i=0;i<=n;i++)
? ?{
? ? ? ?if(a[i]!=0)
? ? ? ?{
? ? ? ? ? ?if(i==meiyoufuhao){
? ? ? ? ? ? ? ?if(abs(a[i])!=1) cout<<a[i];
? ? ? ? ? ? ? ?if(a[i]==-1) cout<<'-';
? ? ? ? ? ?}
? ? ? ? ? ?else if(a[i]>0)
? ? ? ? ? ?{
? ? ? ? ? ? ? ?cout<<'+';
? ? ? ? ? ? ? ?if(abs(a[i])!=1||a[i]==1&&cnt==0) cout<<a[i];
? ? ? ? ? ? ? ?
? ? ? ? ? ?}
? ? ? ? ? ?else
? ? ? ? ? ?{
? ? ? ? ? ? ? ?if(abs(a[i])!=1) cout<<a[i];
? ? ? ? ? ? ? ?if(a[i]==-1)
? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?cout<<'-';
? ? ? ? ? ? ? ? ? ?if(cnt==0) cout<<1;
? ? ? ? ? ? ? ?}
? ? ? ? ? ?}
? ? ? ?}
? ? ? ?if(a[i]!=0&&!cnt==0)
? ? ? ?{
? ? ? ? ? ?if(cnt==1)
? ? ? ? ? ?{
? ? ? ? ? ? ? ?cout<<'x';
? ? ? ? ? ?}
? ? ? ? ? ?else cout<<"x^"<<cnt;
? ? ? ?}
? ? ? ?cnt--;
? ? ? ?
? ?}
? ?return 0;
}