这个题目其实还是算简单的。暴力求解的过程中就可以看出,向上最快能得到的满足条件的数字是第一个非偶数数字加一然后后面全部都是0;向下最快能得到的满足条件的数字是第一个非偶数数字减一然后后面的全是8.所以思路就很明确了,直接定向构造这两个数字,然后和原数做减法,取最小值就行了。不过一开始我没有试29999这样的样例,导致第一遍直接WA掉了。
#include<bits/stdc++.h>
using namespace std;
int main()
{
string num;
long long tmp,ans;
int t;
cin >> t;
for(int kase = 1;kase <= t;kase ++ )
{
cin >> num;
long long a = 0,b = 0;
long long tmp = 0;
bool ok = false;
for(int i = 0;i < num.length();i++)
{
int cur = num[i]-'0';
if(cur%2&&!ok)
{
if(cur == 9)
{
int j;
for(j = i-1;j >= 0;j--)
{
if(num[j] == '8')
a/=10;
else
{
a+=2;
break;
}
}
a+=2;
j = 0;
for(;j <= i;j++)
a*=10;
}
else
a = a*10 + num[i]-'0'+1;
b = b*10+num[i]-'0'-1;
ok = true;
}
else
{
if(!ok){
a = a*10+num[i]-'0';
b = b*10+num[i]-'0';
}
else
{
a = a*10+0;
b = b*10+8;
}
}
tmp = tmp *10 + num[i]-'0';
}
//cout << a << "||" << b << endl;
printf("Case #%d: %lld\n",kase,min(a-tmp,tmp-b));
}
return 0;
}