Given a positive integer x, let P(x) denotes the product of all x's digits. Two integers x and y are friend numbers if P(x) = P(y). Here comes the problem: Given a positive integer x, of course it has a lot of friend numbers, find the smallest one which is greater than x.
Input
There are multiple test cases. The first line of input is an integer T (0 < T < 230) indicating the number of test cases. Then T test cases follow. Each case is an integer x (0 < x <= 101000). You may assume that x has no leading zero.
Output
For each test case, output the result integer in a single line. You should not output a number with leading zero.
Sample Input
3 12 19 222
Sample Output
21 33 241
Author: CAO, Peng
Source: The 7th Zhejiang Provincial Collegiate Programming Contest
题意:告诉你x,找到一个最小的大于x的数y满足,P(x) = P(y)。P(x) 表示 x个数位的乘积
解题思路:
分三种情况讨论
1. 如果只有个位一个0,就从十位上往高位找,找不是9的,找到加1,结束。找的过程遇到9,都改为0。如果都是9,就在数字最左边加一个1。
2. 如果有0,且不是上诉情况,那就直接从个位往高位走,遇到9,变0;遇到非9 ,加1,结束。
3. 如果没有0的话,把从个位开始,素数分解,并记录所有的素数。分解完一位,就判断下分解出来的素数能不能组成比 这一位大的 个位数,能的话取最小的这个数,设这个位为id,接下来从个位,不停地放已经得到的素数能组成最大的数,直到id的后一位为止。如果一直没找到id位,就直接在原来的数前面加个‘1’输出即可。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>
using namespace std;
#define LL long long
const int INF=0x3f3f3f3f;
const int MAX=100009;
int t,len;
char ch[1009];
int cnt[15];
void getnum(int x)
{
if(x==4) cnt[2]+=2;
else if(x==6) cnt[2]++,cnt[3]++;
else if(x==8) cnt[2]+=3;
else if(x==9) cnt[3]+=2;
else cnt[x]++;
}
int check(int x)
{
if(x==1) return 1;
else if(x==4&&cnt[2]>=2)
{
cnt[2]-=2;
return 1;
}
else if(x==6&&cnt[2]&&cnt[3])
{
cnt[2]--;
cnt[3]--;
return 1;
}
else if(x==8&&cnt[2]>=3)
{
cnt[2]-=3;
return 1;
}
else if(x==9&&cnt[3]>=2)
{
cnt[3]-=2;
return 1;
}
else if(cnt[x])
{
cnt[x]--;
return 1;
}
return 0;
}
void add(int x)
{
for(int i=len-1; i>x; i--)
{
for(int j=9; j>=1; j--)
{
if(check(j))
{
ch[i]=j+'0';
break;
}
}
}
}
void put()
{
for(int i=0; i<len; i++)
printf("%c",ch[i]);
printf("\n");
}
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%s",ch);
len=strlen(ch);
int sum=0,k;
for(int i=0; i<len; i++)
{
if(ch[i]=='0')
{
sum=1,k=i;
break;
}
}
if(sum)
{
int p=1,s;
if(k==len-1) s=len-2;
else s=len-1;
while(p&&s>=0)
{
int x=ch[s]-'0'+1;
ch[s]=x%10+'0';
p=x/10;
s--;
}
if(p&&s==-1) printf("1");
put();
}
else
{
memset(cnt,0,sizeof cnt);
getnum(ch[len-1]-'0');
int flag=0;
for(int i=len-2; i>=0; i--)
{
getnum(ch[i]-'0');
for(int j=ch[i]-'0'+1; j<=9; j++)
{
if(check(j))
{
ch[i]=j+'0';
add(i);
flag=1;
break;
}
}
if(flag) break;
}
if(!flag) printf("1");
put();
}
}
return 0;
}