#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
// freopen("1.txt","r",stdin);
int a[1001],t1,t2,flag=0,f=0;
int i=0,n;
char c[1001],temp,buf[1000];
memset(a,0,sizeof(a));
memset(buf,0,sizeof(buf));
fgets(buf,1000,stdin);
n=strlen(buf);
while(i<n-1)
{
t1=0;
t2=0;
if(buf[i]=='-')
{
temp='-';
i++;
}
else if(buf[i]=='+')
{
temp='+';
i++;
}
else
temp='+';
if(buf[i]=='0')
{
i++;
while(buf[i]=='0')
i++;
if(!isdigit(buf[i]))
{
while(buf[i]!='+'&&buf[i]!='-'&& i!=n-1)
i++;
continue;
}
}
while(isdigit(buf[i]))
{
t1=t1*10+(buf[i]-'0');
i++;
}
if(t1==0)
t1=1;
if(buf[i]=='x')
{
i++;
if(buf[i]=='^')
{
i++;
while(isdigit(buf[i]))
{
t2=t2*10+(buf[i]-'0');
i++;
}
if(temp=='+')
a[t2]+=t1;
if(temp=='-')
a[t2]-=t1;
}
else
{
if(temp=='+')
a[1]+=t1;
if(temp=='-')
a[1]-=t1;
}
}
else
continue;
}
for(i=1;i<=1000;i++)
{
if(a[i]!=0)
{
a[i-1]=a[i]*i;
a[i]=0;
}
}
for(i=0;i<1000;i++)
if(a[i]!=0)
{
f=1;
break;
}
for(i=1000;i>=0;i--)
{
if(f==0)
{
printf("%d",f);
break;
};
if(a[i]!=0)
{
if(flag==0 &&a[i]>0)
{
flag=1;
}
else
{
if(a[i]>0)
putchar('+');
flag=1;
}
if(a[i]==-1)
putchar('-');
else if(a[i]!=1)
printf("%d",a[i]);
if(i==0)
break;
putchar('x');
if(i>1)
{
putchar('^');
printf("%d",i);
}
}
}
putchar('\n');
}
修改后运行超时#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
// freopen("1.txt","r",stdin);
int a[1001],b[10],t1,t2,flag=0,f=0;
int i=0,j,n;
char c[1001],temp,buf[1000];
memset(a,0,sizeof(a));
memset(b,-1,sizeof(b));
memset(buf,0,sizeof(buf));
fgets(buf,1000,stdin);
n=strlen(buf);
while(i<n-1)
{
t1=0;
t2=0;
if(buf[i]=='-')
{
temp='-';
i++;
}
else if(buf[i]=='+')
{
temp='+';
i++;
}
else
temp='+';
if(buf[i]=='0')
{
i++;
while(buf[i]=='0')
i++;
if(!isdigit(buf[i]))
{
while(buf[i]!='+'&&buf[i]!='-'&& i!=n-1)
i++;
continue;
}
}
while(isdigit(buf[i]))
{
t1=t1*10+(buf[i]-'0');
i++;
}
if(t1==0)
t1=1;
if(buf[i]=='x')
{
i++;
if(buf[i]=='^')
{
i++;
while(isdigit(buf[i]))
{
t2=t2*10+(buf[i]-'0');
i++;
}
if(temp=='+')
a[t2]+=t1;
if(temp=='-')
a[t2]-=t1;
}
else
{
if(temp=='+')
a[1]+=t1;
if(temp=='-')
a[1]-=t1;
}
}
else
continue;
}
for(j=0,i=1;i<=1000;i++)
{
if(a[i]!=0)
{
f=1;
b[j++]=i-1;
a[i-1]=a[i]*i;
a[i]=0;
}
}
if(f==0)
printf("%d",f);
else
{
for(i=9;i>=0;i--)
{
if(b[i]!=-1)
{
if(flag==0 &&a[b[i]]>0)
{
flag=1;
}
else
{
if(a[b[i]]>0)
putchar('+');
flag=1;
}
if(a[b[i]]==-1)
putchar('-');
else
printf("%d",a[b[i]]);
if(b[i]==0)
break;
putchar('x');
if(b[i]>1)
{
putchar('^');
printf("%d",b[i]);
}
}
}
}
putchar('\n');
}