多项式求和

来源:互联网 发布:淘宝假单号哪里买 编辑:程序博客网 时间:2024/05/15 02:03
这道题很容易超时,当测试了几组比较大的数据之后,发现这道题n的值到了一个界限之后,结果将不再发生变化,所以可以写一个简单的if语句解决这个问题。
#include <iostream>#include <algorithm>#include <string>#include <cstdio>using namespace std;typedef struct node{    int data;    double x;    node *next;}Linklist;Linklist *head, *p, *tail, *q;void nxcreat(int n)///逆序键链表{    head=new Linklist;    head->next=NULL;    while(n--)    {        p=new Linklist;        cin>>p->data;        p->next=head->next;        head->next=p;    }}double sxcreat(int n)  ///顺序建链表{    double a=1, s=0;    head=new Linklist;    head->next=NULL;    tail=head;    for(int i=1;i<=n;i++)    {        p=new Linklist;        if(i%2)        {            p->x=double(1/a);            s+=p->x;            a++;        }        else        {            p->x=double(-1/a);            s+=p->x;            a++;        }        p->next=NULL;        tail->next=p;        tail=p;    }    return s;}void display(){    p=head->next;    while(p->next)    {        printf("%.2lf ", p->x);        p=p->next;    }    cout<<p->x<<endl;}int del1(int n)///单链表重读元素删除{    Linklist *t;    p=head->next;    while(p)    {        t=p;        q=p->next;        while(q)        {            if(p->data==q->data)            {                n--;                t->next=q->next;                free(q);                q=t->next;            }            else            {                q=q->next;                t=t->next;            }        }        p=p->next;    }    return n;}int del2(int n, int key)///删除值为key的节点存在bug, 没有考虑最后一个节点为key要删除情况{    p=head;    while(p->next)    {        if(p->next->data==key)        {            n--;            q=p->next;            p->next=q->next;            free(q);        }        else p=p->next;    }    return n;}double sum(){    double s=0;    p=head->next;    while(p)    {        s+=p->x;        p=p->next;    }    return s;}int main(){    ios::sync_with_stdio(false);    int n, m;    cin>>n;    while(n--)    {        cin>>m;        if(m>=300)///一个简单的if语句            m=300;        printf("%.2lf\n", sxcreat(m));    }    return 0;}

0 0
原创粉丝点击