7-1 一元多项式求导 (20分)
设计函数求一元多项式的导数。
输入格式:
以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。
输出格式:
以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。
输入样例:
3 4 -5 2 6 1 -2 0
输出样例:
12 3 -10 1 6 0
作者
DS课程组
单位
浙江大学
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
Accepted Code
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
//函数状态码定义
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Position;
typedef int ElementType;
struct SNode {
ElementType *Data; //存储元素的数组
Position Top; //栈顶指针
int MaxSize; //堆栈最大容量
};
typedef struct SNode *Stack;
Stack CreateStack( int MaxSize )
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
S->Top = -1;
S->MaxSize = MaxSize;
return S;
}
bool IsFull( Stack S )
{
return (S->Top == S->MaxSize-1);
}
bool Push( Stack S, ElementType X )
{
if ( IsFull(S) ) {
//printf("堆栈满");
return false;
}
else {
S->Data[++(S->Top)] = X;
return true;
}
}
bool IsEmpty( Stack S )
{
return (S->Top == -1);
}
ElementType Pop( Stack S )
{
if ( IsEmpty(S) ) {
//printf("堆栈空");
return ERROR;
}
else
return ( S->Data[(S->Top)--] );
}
Stack Derivation (Stack S1, Stack S2);
int a[1000000];
int main() {
int N = 0, M = 0;
Stack S1, S2, S3;
S1 = CreateStack(1000000);//放系数
S2 = CreateStack(1000000);//放指数
S3 = CreateStack(1000000);
while (scanf("%d%d", &N, &M) != EOF) {
Push(S1, N); //放系数
Push(S2, M); //放指数
}
S3 = Derivation(S1, S2);
int Flag = S3->Top;
if (S3->Top == -1)
printf("0 0");
for (int i = 0; i <= Flag; i++) {
a[i] = Pop(S3);
}
for (int i = 0; i <= Flag; i++) {
printf("%d", a[i]);
if (i <= Flag - 1) printf(" ");
}
}
Stack Derivation (Stack S1, Stack S2) {
Stack S3;
S3 = CreateStack(3000000);
while (!IsEmpty(S1) && !IsEmpty(S2)) {
ElementType coef = 0, index = 0;
coef = Pop(S1);
index = Pop(S2);
if (index != 0) {
Push(S3, index - 1);
Push(S3, coef * index);
}
}
return S3;
}
仅供参考