PAT (Basic Level) Practice 1010

1010. Unary Polynomial Derivation(25)

time limit
400 ms
memory limit
65536 kB
code length limit
8000 B
Judgment procedure
Standard

Design a function to take the derivative of a polynomial in one variable. (Note: the first derivative of x n (n is an integer) is n*x n-1 .)

Input format: Input the non-zero coefficients and exponents of the polynomial in exponential descending mode (the absolute values ​​are integers not exceeding 1000). The numbers are separated by spaces.

Output Format: Output the coefficients and exponents of the non-zero terms of the derivative polynomial in the same format as the input. Numbers are separated by spaces, but no extra spaces at the end. Note that the "zero polynomial" has both exponents and coefficients 0, but is represented as "0 0".

Input sample:
3 4 -5 2 6 1 -2 0
Sample output:
12 3 -10 1 6 0

Analysis: The question that was supposed to be very simple, I made a double iterator to write, and it was very disgusting. Although it's been over... and then I suddenly realized that this question doesn't need to be so hard. Don't talk about the disgusting, talk about the normal one. Set an indicator to indicate whether it is the first output, if it is, the indicator is converted, otherwise the output space is used to separate each group of numbers. Output "0 0" when only one set of constants or derivatives is zero.

Code (the disgusting one):

#include<iostream>
#include<vector>
#include<utility>
using namespace std;
intmain()
{
	pair<int, int> p;
	vector<pair<int, int> > vi;
	vector<vector<pair<int, int> >::iterator> vit;
	while(cin >> p.first >> p.second){
		vi.push_back(p);
	}
	for(vector<pair<int, int> >::iterator it = vi.begin(); it != vi.end(); it++){
		if((*it).second != 0){
			(*it).first *= (*it).second;
			(*it).second--;
		}else if(vi.size() == 1 && (*it).second == 0){
			(*it).first = 0;
		}else if((*it).first != 0 && (*it).second == 0){
			vit.push_back(it);
		}
	}
	for(vector<vector<pair<int, int> >::iterator>::iterator it = vit.begin(); it != vit.end(); it++){
		vi.erase (* it);
	}
	for(vector<pair<int, int> >::iterator it = vi.begin(); it != vi.end(); it++){
		if(it != vi.end() - 1){
			cout << (*it).first << ' ' << (*it).second << ' ';
		}else{
			cout << (*it).first << ' ' << (*it).second << endl;
		}
	}
	return 0;
}

Code (the normal one):

#include<iostream>
using namespace std;
intmain()
{
	int a, b;
	int flag = 1;
	while(cin >> a >> b){
		if(a * b != 0){
			if(flag == 0){
				cout << ' ';
			}else{
				flag = 0;
			}
			cout << a * b << ' ' << b - 1;
		}
	}
	if(flag == 1){
		cout << "0 0";
	}
	cout << endl;
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324525355&siteId=291194637
Recommended