#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAX(a, b) (a > b)? a: b
#define MIN(a, b) (a < b)? a: b
#define MAX_N 105
using namespace std;
char str[MAX_N];
int use[MAX_N];
int c4, c7, l;
bool change(int x) {
if (x == 0) return true;
if (str[x - 1] == '4') {
str[x - 1] = '7';
l = x - 1;
return false;
}
else return change(x - 1);
}
int main() {
//freopen("e:\\ACM\\duipai\\data.txt", "r", stdin);
//freopen("e:\\ACM\\duipai\\out1.txt", "w", stdout);
while (cin>>str) {
//flag标记是否可以有与输入数位数相同的super lucky,vis 标记是否最小的数字选择大于其的
bool flag = false, vis = false;
int len = strlen(str);
//奇位数直接跳过
if (len % 2 == 1) flag = true;
if (!flag) {
//用c4,c7表示47各自剩余的数
c4 = len / 2, c7 = len / 2;
for (int i = 0; i < len; i++) {
//小于等于4,或者被标记,且还有4可以用,进入
if ((str[i] <= '4' || vis) && c4) {
//如果最低选择位小于4,标记
if (str[i] < '4') vis = true;
str[i] = '4';
c4--;
}
//7有剩余,被标记过或者位于4—7之间。
else if (c7 && (vis || str[i] <= '7')) {
if (str[i] < '7') vis = true;
str[i] = '7';
c7--;
}
else {
//向上查找,有4换为7,否则跳出。
if(flag = change(i)) break;
else {
i = l;
//从新取c4,c7的值应用
c4 = use[i] / 100 + 1;
c7 = use[i] % 100 - 1;
vis = true;
}
}
//用use记录各个状态的c4,与c7的值,方便再次调用
use[i] = c4 * 100 + c7;
if (c7 == -1) {
flag = true;
break;
}
}
}
if (flag) {
if (len % 2 == 0) printf("4");
for (int i = 0; i < (len + 1) / 2; i++) {
printf("4");
}
for (int i = 0; i < (len + 1) / 2; i++) {
printf("7");
}
if (len % 2 == 0) printf("7");
}
else {
for (int i = 0; i < len; i++) {
printf("%c", str[i]);
}
}
printf("\n");
}
return 0;
}
CodeForces - 96B Lucky Numbers (easy)
最新推荐文章于 2019-10-14 22:52:52 发布