您的位置:首页 > 大数据 > 人工智能

2016 Winter Training Day #1_E题_codefcrces 514A(贪心)

2016-01-21 19:40 465 查看
A. Chewbaсca and Number

time limit per test
1 second

memory limit per test
256 megabytes

input
standard input

output
standard output

Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means
replacing it with digit 9 - t.

Help Chewbacca to transform the initial number x to the minimum possible positive number
by inverting some (possibly, zero) digits. The decimal representation of the final number shouldn't start with a zero.

Input

The first line contains a single integer x (1 ≤ x ≤ 1018) —
the number that Luke Skywalker gave to Chewbacca.

Output

Print the minimum possible positive number that Chewbacca can obtain after inverting some digits. The number shouldn't contain leading zeroes.

Sample test(s)

input
27


output
22


input
4545


output

4444

题意:给出一个数字,对这个数字的每一位都可以有两个操作:保持原数字,或者翻转(用9减该位数字)。求最后求出来的数字的最小值。

思路:简单贪心,只需要每一位数字都最小,则整个数字肯定最小。对每一位数字都取 min(a, 9-a)就ok了,非常简单,但我用字符串做的时候,总是输出不了样例。

错误代码:

for(int i = 0; i < s.size(); ++i)

s[i] = min(s[i], '9'-s[i]);

cout << s << endl;

错误原因:对ASCII码不够熟悉,'9'-s[i] 得出来的是 数字 1 2 3 4 5 .... 而不是字符 ‘1’‘2’,所以还应该改为

s[i] = min(s[i], '9'-s[i]+'0')

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>

using namespace std;

const int INF = 0x7fffffff;

int main()
{

char s[20];

cin >> s;
int n = strlen(s);
for(int i = 0; i < n; ++i)
{

if(i == 0 && s[i] == '9')
continue;
else
{
if(s[i] >= '5')
s[i] = '9'- s[i] +'0';
else
continue;

}

}
cout << s << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: