#697. noip2000普及组第一�

Luogu:P1022 [NOIP2000 普及组] 计算器的改良 - 洛谷 | 计算机科学教育新生� (luogu.com.cn)

提交记录: BNDSOJ for Homework - BNDS Online Judge

 

说实话,这道题难度一点也不是普及组第一题的难度,难度已经到第三题了。我第一次提交时只得�80分,最后一个点很坑�

input:

-a+1a-3=a-3

output:

a=-0.000

result:

wrong answer 1st words differ - expected: 'a=0.000', found: 'a=-0.000'

最后一个答案四舍五入为0.000,但double计算中的精度问题导致答案算完可能�-0.000001,printf会输�-0.000导致错误。只能在最后特判一下�

 

思路�

首先输入整理出结构体形式的多项式,把项全部移动到等号右边�

6a-5+1=2-2a ------------------>> 6a-5+1-2+2a=0

再把一次项和常数项整理出来�

6a-5+1-2+2a=0 ----------->> (6+2)a+(-5+1-2)=0 ----------->> 8a-6=0

最后将一次项系数除以负的常数项系数,

8a-6=0 ------------------>> 8 / -(-6)=8/6=-0.75

然后输出它就可以了�

 

代码�

#include <bits/stdc++.h> using namespace std; //ax^flag struct node { int a = 0; bool flag; }; vector<node> fun; char the_x; //done //处理单项� //flag == true, 在等号左边,否则在等号右� void mk(string str, bool flag) { bool flag999 = false; int p = 0; node nd; if(str[p] == '+' || str[p] == '-') p++; if(p == 1 && str[p - 1] == '-') flag999 = true; while(str[p] >= '0' && str[p] <= '9' && p < str.length()) { nd.a *= 10; nd.a += str[p] - '0'; p++; } if(p == str.length()) nd.flag = false; else { if(str[p] >= 'a' && str[p] <= 'z') the_x = str[p], nd.flag = true; } if(!flag) nd.a *= -1; if(flag999) nd.a *= -1; fun.push_back(nd); // printf("get new nd->a = %d, flag = %d\n", nd.a, nd.flag); } //done char first_str() { char next; string str; str.push_back(getchar()); while(true) { char ch = getchar(); if(ch == '+' || ch == '-' || ch == '=') { next = ch; break; } str.push_back(ch); } // cout << str << endl; mk(str, true); return next; } pair<char, string> get_next() { char next; string str; while(true) { char ch = getchar(); if(ch == '+' || ch == '-' || ch == '=' || ch == '\n' || ch == 'EOF' || ch == '\0') { next = ch; break; } str.push_back(ch); } // cout << str << endl; return {next, str}; } bool cmp(node a, node b) { if(a.flag == b.flag) return true; if(a.flag == true) return true; return false; } int main() { bool flag233 = true;//等号左右� char ch = first_str(); if(ch == '=') flag233 = false; // cout << "next->" << ch << endl; while(true){ pair<char, string> ret = get_next(); if(ch == '-') ret.second = "-" + ret.second; ch = ret.first; // cout << "ret.first->" << ret.first << " ret.second->" << ret.second << endl; mk(ret.second, flag233); if(ch == '\n' || ch == 'EOF' || ch == '\0') break; if(ch == '=') flag233 = false; } // sort(fun.begin(), fun.end(), cmp); // for(int i = 0; i < fun.size(); i++) { // if(fun[i].a >= 0) printf("+%dx^%d", fun[i].a, fun[i].flag); // else if(fun[i].a < 0) printf("%dx^%d", fun[i].a, fun[i].flag); // } // cout << endl; double nd1, nd0; for(int i = 0; i < fun.size(); i++) { if(fun[i].flag) { nd1 += fun[i].a; } else nd0 += fun[i].a; } // cout << "nd0->" << nd0 << " nd1->" << nd1 << endl; nd0 = -nd0; double ans = nd0 / nd1; if(abs(ans) > 0.001) printf("%c=%.3lf\n", the_x, ans); else printf("%c=0.000\n", the_x); return 0; }