时间限制 | 内存限制 |
---|---|
1000 ms |
65536 KB |
# 题目描述
在一次数析课上,Paradise 将分子分母同时出现的微分约掉了,进而证明了 ,创造了这个世界上最伟大的奇迹......
于是期末这门课挂掉了一位
重修一学期,Paradise 痛定思痛,想要拿到学分
这天老师留了一道题,是求一个多项式的一阶导数!但 Paradise 却呆住了,这该怎么做呀!于是将问题转交给了你。
# 输入
一行,一个以 f(x)=
开头的字符串,后面有多个项相加,每一个非常数项都是 x
、 ax
、 x^b
或 ax^b
的格式,其中 都是正整数,如果不存在则表示 ,否则表示 ,每项之间用 +
连接,代表加法。多项式一定是降幂排列的
所有的 都满足
# 输出
一行,一个以 f'(x)=
开头的字符串,后面格式与输入相同,表示多项式的导数
# 输入样例
f(x)=x^3+3x^2+6 |
# 输出样例
f'(x)=3x^2+6x |
# 题解:模拟
比较复杂的模拟所以这里梳理一下模拟的思路:
将字符串按 +
号分成若干段,对每一段进行求导。
求导的时候判断是否包含 ,这一部分有太多的细节,具体的还是参考代码吧。
参考代码:
#include <stdio.h> | |
#include <string.h> | |
#include <stdbool.h> | |
#include <ctype.h> | |
char str[500010]; | |
bool isFirst = true; | |
void Process(int l, int r) | |
{ | |
bool isDigit = true; | |
for (int i = l; i <= r; ++ i) | |
if (!isdigit(str[i])) | |
{ | |
isDigit = false; | |
break; | |
} | |
if (isDigit) | |
{ | |
if (isFirst) | |
putchar('0'); | |
return; | |
} | |
int xIndex = 0; | |
for (int i = l; i <= r; ++ i) | |
if (str[i] == 'x') | |
{ | |
xIndex = i; | |
break; | |
} | |
int co = 0, power = 0; | |
if (xIndex == l) | |
co = 1; | |
else | |
{ | |
for (int i = l; i < xIndex; ++ i) | |
co = co * 10 + str[i] - '0'; | |
} | |
if (xIndex == r) | |
power = 1; | |
else | |
{ | |
for (int i = xIndex + 2; i <= r; ++ i) | |
power = power * 10 + str[i] - '0'; | |
} | |
if (!isFirst) | |
putchar('+'); | |
if (co * power != 1 || (co * power == 1 && power - 1 == 0)) | |
printf("%d", co * power); | |
if (power - 1 > 0) | |
putchar('x'); | |
if (power - 1 > 1) | |
printf("^%d", power - 1); | |
isFirst = false; | |
return; | |
} | |
int main() | |
{ | |
// freopen("F.in", "r", stdin); | |
// freopen("F.out", "w", stdout); | |
scanf("%s", str); | |
printf("f'(x)="); | |
int l = 5, r = 5, len = strlen(str); | |
while (r < len) | |
{ | |
if (str[r] == '+') | |
{ | |
Process(l, r - 1); | |
l = r + 1; | |
} | |
++ r; | |
} | |
Process(l, r - 1); | |
return 0; | |
} |