PAT-Basic-1010


PAT乙级-1010


题目分析

 本题有两个难点。

 其一、数据的读入。因为题目没有指明输入多项式的项数,所以需要使用while语句来完成读入。

 其二、求导的算法。可以使用一个数组来存储从0到可能最大次幂1000的所有项的系数,然后用一遍循环来完成求导。但是这种方法会占用相对较大的内存,而且时间复杂度也不是最优的。由于求导过程中各加项是相对独立的,因此只需要用两个变量来边读入边打印即可。一个int index用于记录当前读入项的幂指数,一个int coef用于记录当前项的系数。每次连续读入两个数,进行单项的求导然后判断输出。

 题目中要求对于零多项式要特殊处理,因此需要额外对其进行判断。分析可知,只有当一次及以上的项系数都为0时,求导得到零多项式,此时输入只有一项,可以通过一个bool first来判定零多项式。此外first还可以用于调整输出格式。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "iostream"
#include "cstdio"
using namespace std;

int main(){
int coef, index;
bool first = true;
do{
cin >> coef >> index;
coef *= index;
if(coef == 0 && index == 0 && first){
cout << 0 << " " << 0;
return 0;
}
index--;
if(index < 0) break;
if(first){
cout << coef << " " << index;
first = false;
}
else
cout << " " << coef << " " << index;
}while(getwchar() != '\n');
return 0;
}

转载 请注明来源:©Tinshine