您的位置:首页 > 其它

Codeforces Round #350 (Div. 2) F. Restore a Number

2016-05-09 18:18 351 查看

F. Restore a Number

Vasya decided to pass a very large integer n to Kate. First, he wrote that number as a string, then he appended to the right integer k — the number of digits in n.

Magically, all the numbers were shuffled in arbitrary order while this note was passed to Kate. The only thing that Vasya remembers, is a non-empty substring of n (a substring of n is a sequence of consecutive digits of the number n).

Vasya knows that there may be more than one way to restore the number n. Your task is to find the smallest possible initial integer n. Note that decimal representation of number n contained no leading zeroes, except the case the integer n was equal to zero itself (in this case a single digit 0 was used).

Input
The first line of the input contains the string received by Kate. The number of digits in this string does not exceed 1 000 000.

The second line contains the substring of n which Vasya remembers. This string can contain leading zeroes.

It is guaranteed that the input data is correct, and the answer always exists.

Output
Print the smalles integer n which Vasya could pass to Kate.

Examples

input
003512
021


output
30021


input
199966633300
63


output
3036366999


/*这代码真丑*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1e6+15;
char s[maxn],sub[maxn],ans[2][maxn];
int cnt[10],len,sublen;
bool jud(int n)
{
bool ok=1;
int x=n,k=0;
while(x)
{
if(cnt[x%10]<=0)ok=0;
cnt[x%10]--;
x/=10;
k++;
}
if(ok&&len-k==n)
return 1;
x=n;
while(x)
{
cnt[x%10]++;
x/=10;
}
return 0;
}
int main()
{
int i,flag;
scanf("%s%s",s,sub);
len=strlen(s);
sublen=strlen(sub);
for(i=1;i<sublen;i++)
if(sub[i]!=sub[i-1])
{
if(sub[i]<sub[i-1])flag=-1;
else flag=1;
break;
}
for(i=0;i<len;i++)
cnt[s[i]-'0']++;
for(i=0;i<sublen;i++)
cnt[sub[i]-'0']--;
for(i=sublen;i<=len;i++)
if(jud(i))break;
for(i=1;i<10;i++)
if(cnt[i])break;
if(sub[0]=='0')
{
if(i==10)
{
puts("0");
return 0;
}
printf("%c",i+'0');
cnt[i]--;
while(cnt[0]--)printf("0");
printf("%s",sub);
for(int j=1;j<10;j++)
while(cnt[j]--)printf("%c",j+'0');
return 0;
}
if(i==10)
{
printf("%s",sub);
while(cnt[0]--)printf("0");
return 0;
}
int k=0,x;
ans[0][k++]=i+'0';
cnt[i]--;
for(int j=0;j<10;j++)
{
int x=cnt[j];
if(j==sub[0]-'0')
{
if(flag==-1)
{
for(int t=0;t<sublen;t++)ans[0][k++]=sub[t];
while(x>0)ans[0][k++]=j+'0',x--;
}
else
{
while(x>0)ans[0][k++]=j+'0',x--;
for(int t=0;t<sublen;t++)ans[0][k++]=sub[t];
}
}
else while(x>0)ans[0][k++]=j+'0',x--;
}
cnt[i]++;
ans[0][k]='\0';
k=0;
for(int t=0;t<sublen;t++)ans[1][k++]=sub[t];
for(int j=0;j<10;j++)
{
int x=cnt[j];
while(x>0)ans[1][k++]=j+'0',x--;
}
ans[1][k]='\0';
puts(strcmp(ans[0],ans[1])<0?ans[0]:ans[1]);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: