相等的多项式(C++实训题)

写在前面:仅为个人代码/总结,未必标准,仅供参考!如有错误,还望指出交流,共同进步!

相等的多项式

【问题描述】
小明现在在学习多项式的展开:就是把一个形如
(x+a1) (x+a2) … (x+an)
展开成如下形式:
xn + b1xn-1 + b2xn-2 + … + bn-1x + bn
比如 (x+1)(x+2)=x2 + 3x + 2
(x+1)3 = x3 +3x2 +3x + 1
小明做了很多练习,但是不知道对错,现在请求你的帮助,判断小明的展开式是否正确。

【输入格式】
有多组测试数据。
每组测试数据有三行,第一行是一个正整数N,表示多项式最高指数。N=0表示输入结束,并且不需要处理。
第二行N个整数ai,用空格隔开,i=1,…,N(-100≤ai≤100)
第三行N个整数bi,用空格隔开,i=1,…,N,(-109≤bi≤109)
40%的测试数据 1 ≤ N < 5;
30%的测试数据 5 ≤ N < 10;
20%的测试数据10 ≤ N < 15;
10%的测试数据 15 ≤N≤ 20;

【输出格式】
对于每组测试数据,输出一行一个字符‘Y’如果展开式是正确的,输出‘N’如果展开式错误。

【样例输入】
2
1 2
3 2
3
1 1 1
3 3 1
4
0 0 0 1
0 0 0 1
0

【样例输出】
Y
Y
N

【思路】
简单的做法就是模拟多个多项式的乘法计算过程

【示例代码】

#include <bits/stdc++.h>
using namespace std;
struct item
{
    
    
    int xi;//系数
    int mi;//幂
};
int main()
{
    
    
    while(1)
    {
    
    
        int n;
        cin>>n;
        if(n==0) {
    
    break;}
        int a,b[n];
        vector <item> N;
        item temp;
        temp.mi=1;
        temp.xi=1;
        N.push_back(temp);
        //模拟计算过程
        for(int i=0;i<n;i++)
        {
    
    
            cin>>a;
            if(i==0)
            {
    
    
                temp.mi=0;
                temp.xi=a;
                N.push_back(temp);
            }
            else
            {
    
    
                int len=N.size();
                vector <item> M;
                M.assign(N.begin(),N.end());
                for(int j=0;j<len;++j)
                {
    
    
                    N[j].mi++;
                }
                for(int j=1;j<len;j++)
                {
    
    
                    N[j].xi+=a*M[j-1].xi;
                }
                temp.xi=M[len-1].xi*a;
                temp.mi=0;
                N.push_back(temp);
            }
        }
        bool flag=true;
        for(int i=0;i<n;i++)
        {
    
    
            cin>>b[i];
            if(b[i]!=N[i+1].xi)
            {
    
    
                flag=false;
            }
        }
        if(flag) {
    
    cout<<"Y"<<endl;}
        else {
    
    cout<<"N"<<endl;}
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45909595/article/details/108023171