1544. Integer Generator
限制条件
时间限制: 1 秒, 内存限制: 32 兆
题目描述
As part of a larger scale project, you need to write a component which generates consecutive positive integers. Only certain digits may appear in the input and in the integers generated, and leading zeros aren't allowed.
You are given a list of allowed digits, and a String current representing the current integer. Fine the next integer larger than current composed only of digits allowed.
输入格式
Input contain multiple cases, each in two line. The first line contain a string, which represents the list of allowed digits. The second line contain the string current. The list of allowed digits will contain between 1 and 10 elements, inclusive, Each element in the list will be between "0" and "9", inclusive. The list contain no dulplicates. current will contain between 1 and 10 digits ('0'-'9'), inclusive. Process to the end of input.
输出格式
For each case, output one line containing the desired integer. If current is invalid itself, ouput one line "INVALID INPUT" instead.
样例输入
0123456789 16 012345689 16 358 548 534 033 9876543210 999 012345 0 1 1
样例输出
17 18 INVALID INPUT INVALID INPUT 1000 INVALID INPUT 11这题整体来说不算难,但是感觉很难写,开始用得到数之后逐个加一然后直到满足check条件为止,但事实证明,这样做,是超时的。
第二种思路可以0秒AC,首先将给的模版字符串进行排序,然后我们从低位逐个替换输入的字符串,知道满足大于条件为止。但是这样做就得考虑要是得不到这样条件的字符串怎么办,那么就说明这个位数的不能够满足,我们构造一个大于这个位数的最小数就好,比如三位数不能满足,我们造一个满足条件的最小四位数就行了。
#include <iostream>
#include <map>
#include <cstdio>
#include <vector>
#include <cmath>
#include <iomanip>
#include <sstream>
#include <string>
#include <list>
#include <queue>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#define N 501
using namespace std;
bool check(char a[],char b[])
{
if(b[0] == '0') return false;
map<char,bool> f;
for(int i=0;i<strlen(a);i++)
f[a[i]] = true;
int cnt = 0;
for(int i=0;i<strlen(b);i++)
if(f[b[i]]) cnt++;
if(cnt == strlen(b)) return true;
else return false;
}
int cmp(char a[],char b[])
{
int l1 = strlen(a);
int l2 = strlen(b);
if(l1 > l2) return 1;
else if(l1 < l2) return -1;
else
{
for(int i=0;i<l1;i++)
{
if(a[i] > b[i]) return 1;
else if(a[i] < b[i]) return -1;
}
}
return 0;
}
int main()
{
char a[1000],input[1000];
while(scanf("%s%s",a,input) != EOF)
{
if(!check(a,input))
printf("INVALID INPUT\n");
else
{
sort(a,a+strlen(a));
bool bo = 0;char tem[1000];
strcpy(tem,input);
for(int i=strlen(input)-1;i>=0;i--)
{
for(int j=0;j<strlen(a);j++)
{
tem[i] = a[j];
if(cmp(tem,input) > 0)
{
bo = 1;
printf("%s\n",tem);
break;
}
if(bo == 0 && j == strlen(a)-1)
{
tem[i] = a[0];
}
}
if(bo) break;
}
if(bo == 0)
{
if(a[0] == '0')
{
printf("%c",a[1]);
for(int i = 0;i<strlen(input);i++)
{
printf("%c",a[0]);
}
}
else {
for(int i = 0;i<=strlen(input);i++)
{
printf("%c",a[0]);
}
}
printf("\n");
}
}
}
return 0;
}