A. Efim and Strange Grade
Efim just received his grade for the last test. He studies in a special school and his grade can be equal to any positive decimal fraction. First he got disappointed, as he expected a way more pleasant result. Then, he developed a tricky plan. Each second, he can ask his teacher to round the grade at any place after the decimal point (also, he can ask to round to the nearest integer).
There are t seconds left till the end of the break, so Efim has to act fast. Help him find what is the maximum grade he can get in no more than t seconds. Note, that he can choose to not use all t seconds. Moreover, he can even choose to not round the grade at all.
In this problem, classic rounding rules are used: while rounding number to the n-th digit one has to take a look at the digit n + 1. If it is less than 5 than the n-th digit remain unchanged while all subsequent digits are replaced with 0. Otherwise, if the n + 1 digit is greater or equal to 5, the digit at the position n is increased by 1 (this might also change some other digits, if this one was equal to 9) and all subsequent digits are replaced with 0. At the end, all trailing zeroes are thrown away.
For example, if the number 1.14 is rounded to the first decimal place, the result is 1.1, while if we round 1.5 to the nearest integer, the result is 2. Rounding number 1.299996121 in the fifth decimal place will result in number 1.3.
题目大意
给你一个小数,你可以对小数点后的任一数字做四舍五入,现在给你t次机会,要求t次后这个小数最大。
题解
初看题目好像挺复杂的,但分析一下发现,只需要找到离小数点最近的可以进行四舍五入的数字一直向前进行四舍五入就可以了,做不下去就停下。
代码如下:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int a[300010];
int n,t,key,start,j;
string s;
int maintain(int k)
{
while(1)
{
if(k==key) { k++; continue; }
if(a[k]<10) break;
else { a[k+1]++; a[k]=0; k++; }
}
if(k>j) j=k;
return k;
}
int main()
{
key=start=-1;
cin >>n>>t>>s;
for(int i=0;i<s.length();i++)
{
if(s[i]=='.') { key=i; continue; }
if(key!=-1&&s[i]>='5') { start=i; break; }
}
if(start==-1)
{
cout <<s<<endl;
return 0;
}
for(int i=start;i>=0;i--)
{
if(s[i]=='.') { key=j; a[j++]=-1; continue; }
a[j++]=s[i]-'0';
}
j--;
for(int i=0;t>0;t--)
{
if(i>=key) break;
else if(a[i]<=4) break;
else
{
int re=(i+1==key ? i+2 : i+1 );
a[re]++;
a[i]=0;
i=maintain(re);
}
}
s.clear();
t=0;
for(int i=0;i<=j;i++)
{
if(t==0&&(a[i]>0||i>key)) t=1;
if(t==1)
{
if(a[i]==-1) s+='.';
else s+=(char)(a[i]+'0');
}
}
for(int i=s.length()-1;i>=0;i--) cout <<s[i];
cout <<endl;
return 0;
}