PAT 1002 A+B for Polynomials

刚看到这道题的时候,曾一度感觉是对应n相加,没有想到是多项式加法,后来在网上看了他们的,感觉这个比较像多项式加法(AN为系数,N为指数)。啊~~~明白了之后终于AC了附上源码,比较麻烦的源码

/*这道题的意思是多项式加法an对应系数,n对应幂
这里是先用结构体链表接收数据,然后再将结构体的数据转给结构体数组调用
qsort方法进行排序输出
*/
#include<stdio.h>
#include<stdlib.h>
struct Demo
{
    int n;
    double an;
    struct Demo *next;
};

struct Task
{
    int x;
    double y;
}T[30];


int cmp(const void *a,const void *b)
{
    struct Task *aa=(struct Task *)a;
    struct Task *bb=(struct Task *)b;
    return bb->x-aa->x;
}


int main()
{
    struct Demo *head,*p,*rear,*q;
    int k;
    int i;
    int a;
    int cunt=0;
    int tempcunt=0;
    double b;
    int flag;
    scanf("%d",&k);
    head=(struct Demo*) malloc (sizeof(struct Demo));
    rear=head;
    for(i=0;i<k;i++)
    {
        p=(struct Demo *)malloc(sizeof(struct Demo));
        scanf("%d %lf",&a,&b);
        p->n=a;
        p->an=b;
        rear->next=p;
        rear=p;
    }
    rear->next=NULL;

    scanf("%d",&k);
    q=head->next;
    for(i=0;i<k;i++)
    {
        flag=0;
        scanf("%d %lf",&a,&b);
        while(q)
        {
            if(q->n==a)
            {
                q->an+=b;
                flag=1;
                break;
            }
            q=q->next;
        }
        if(!flag)
        {
            p=(struct Demo *)malloc(sizeof(struct Demo));
            p->n=a;
            p->an=b;
            rear->next=p;
            rear=p;
            q=head->next;
        }
        rear->next=NULL;
    }
    p=head->next;
    cunt=0;
    while(p)
    {
        T[cunt].x=p->n;
        T[cunt].y=p->an;
        if(p->an==0) tempcunt++;
        cunt++;
        p=p->next;
    }
    printf("%d",cunt-tempcunt);
    qsort(T,cunt,sizeof(T[0]),cmp);
    for(i=0;i<cunt;i++)
    {
        if(T[i].y!=0) printf(" %d %.1lf",T[i].x,T[i].y);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值