1170: 多项式相加

来源:互联网 发布:嵌入式linux内核开发 编辑:程序博客网 时间:2024/06/04 19:14

题目

Description

一条单链表可以表示一个一元多项式,每个节点包含三个域:指数、系数和后继节点(指针或引用)。

表示多项式3X4-6X2+5X-10的单链表如图所示。给定两个多项式,实现两个多项式相加算法。

Input

第一行输入包含两个整数m,n

后续为m行和n行数据

m,n分别代表两个多项式的项数

后续每一行代表多项式的项,包含a,b两个数据,表示该项的系数和指数。

Output

从较高指数到较低指数,依次输出求得的和。

每行一项,格式与输入相同,但无需输出项数,系数为0的项也不输出。

Sample Input

2 3
1 2
1 1
2 2
1 1
2 0
Sample Output

3 2
2 1
2 0


代码块

import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner cn = new Scanner(System.in);        int m = cn.nextInt();        int n = cn.nextInt();        Poly[] po = new Poly[m+n];//建立一个类,数组        for (int i = 0; i < n+m; i++) {            int coe = cn.nextInt();            int exp = cn.nextInt();            po[i] = new Poly(coe, exp);//将输入的所有多类项,放在一个类数组中        }        for(int i =0;i<n+m;i++){//对类数组,进行排序            for(int j = i+1;j<n+m;j++){                if(po[i].getExp()<po[j].getExp()){                    Poly pl = po[j];                    po[j] = po[i];                    po[i] =pl;                }else if(po[i].getExp()==po[j].getExp()){//如果后面的指数相同者,将,项数加在一起,放在前面的类中,并将后面的指数对应的项数,进行设置为0                    po[i].setCoe(po[i].getCoe()+po[j].getCoe());                    po[j].setCoe(0);                }            }        }        for(int i = 0;i<n+m;i++){//系数为0的不输出,即可            if(po[i].getCoe()==0) continue;            System.out.println(po[i].getCoe()+" "+po[i].getExp());        }    }}class Poly {    private int Exp;    private int Coe;    public Poly(int Coe, int Exp) {        this.Exp = Exp;        this.Coe = Coe;    }    public void setExp(int Exp){        this.Exp = Exp;    }    public void setCoe(int Coe){        this.Coe = Coe;    }    public int getExp() {        return this.Exp;    }    public int getCoe() {        return this.Coe;    }}
原创粉丝点击