Arithmetic Expression
时间限制:2000ms
单点时限:200ms
内存限制:256MB
描述
Given N arithmetic expressions, can you tell whose result is closest to 9?
输入
Line 1: N (1 <= N <= 50000).
Line 2..N+1: Each line contains an expression in the format of "a op b" where a, b are integers (-10000 <= a, b <= 10000) and op is one of addition (+), subtraction (-), multiplication (*) and division (/). There is no "divided by zero" expression.
输出
The index of expression whose result is closest to 9. If there are more than one such expressions, output the smallest index.
- 样例输入
-
4 901 / 100 3 * 3 2 + 6 8 - -1
- 样例输出
-
2
【题意】:算出的结果最接近9的为第几个,相同的话输出靠前的。注意卡精度!要用double~
【代码】:#include <bits/stdc++.h> #define LL long long #define maxn 500005 const int inf = 0x3f3f3f3f; using namespace std; int n,idx; double a,b,sum=0; char op; double mi=0x3f3f3f3f3f; void cal() { switch(op) { case '+': sum=a+b; break; case '-': sum=a-b; break; case '*': sum=a*b; break; case '/': sum=a/b; break; } } int main() { cin>>n; for(int i=1;i<=n;i++) { cin>>a>>op>>b; cal(); double now = abs(9-sum); if(now < mi)//在线查询,边输入边查询,也可以叫打擂台算法,谁小谁上当min King,并记录是第几个人 { idx=i;//而且是now < mi 不能等于,无形记录了字典序最小的那个人,因为后面出现的也是相等,不是小于了! mi=now; } } cout<<idx<<endl; }