SHOW:
|
|
- or go back to the newest paste.
| 1 | #include<iostream> | |
| 2 | #include<map> | |
| 3 | #include<string> | |
| 4 | #include<sstream> | |
| 5 | #include<regex> | |
| 6 | ||
| 7 | std::string derivative(std::string polynomial) {
| |
| 8 | std::regex m("[+]?([-]?[0-9]*)[\\*]?(x?)[\\^]?([0-9]*)");
| |
| 9 | std::smatch sm; | |
| 10 | std::map<int, int> pow_k; | |
| 11 | ||
| 12 | while(regex_search(polynomial, sm, m) && polynomial.size() > 0) | |
| 13 | {
| |
| 14 | int k = atoi(std::string(sm[1]).c_str()); | |
| 15 | int pow = atoi(std::string(sm[3]).c_str()); | |
| 16 | if (std::string(sm[2]) == "x") | |
| 17 | {
| |
| 18 | if (pow == 0) pow = 1; | |
| 19 | if (k == 0) k = 1; | |
| 20 | if (std::string(sm[1]) == "-") k = -1; | |
| 21 | } | |
| 22 | ||
| 23 | pow_k[pow] += k; | |
| 24 | polynomial = sm.suffix(); | |
| 25 | } | |
| 26 | ||
| 27 | std::ostringstream result; | |
| 28 | auto begin = pow_k.rbegin(); | |
| 29 | auto end = pow_k.rend(); | |
| 30 | auto gets = [](int pow, int k){
| |
| 31 | std::ostringstream member; | |
| 32 | member << k * pow; | |
| 33 | if (pow > 1) member << "*x"; | |
| 34 | if (pow > 2) member << '^' << pow-1; | |
| 35 | return member.str(); | |
| 36 | }; | |
| 37 | if (begin != end) | |
| 38 | {
| |
| 39 | result << gets( begin->first, begin->second ); | |
| 40 | ++begin; | |
| 41 | } | |
| 42 | for(; begin != end; ++begin) | |
| 43 | {
| |
| 44 | if ( begin->first == 0 ) continue; | |
| 45 | if ( begin->second > 0 ) result << '+'; | |
| 46 | result << gets( begin->first, begin->second ); | |
| 47 | } | |
| 48 | return result.str(); | |
| 49 | } | |
| 50 | ||
| 51 | int main() | |
| 52 | {
| |
| 53 | #ifdef AZHUKOV | |
| 54 | freopen("input.txt", "r", stdin);
| |
| 55 | #endif | |
| 56 | std::string in; | |
| 57 | std::cin >> in; | |
| 58 | std::cout << derivative(in) << std::endl; | |
| 59 | return 0; | |
| 60 | } |