原文:
D. Required Length
You are given two integer numbers, n and x. You may perform several operations with the integer x.
Each operation you perform is the following one: choose any digit y that occurs in the decimal representation of x at least once, and replace x by x⋅y⋅.
You want to make the length of decimal representation of x (without leading zeroes) equal to n. What is the minimum number of operations required to do that?
Input
The only line of the input contains two integers n and x ( 2≤n≤19 ; 1≤x<10^(n−1) ).
Output
Print one integer — the minimum number of operations required to make the length of decimal representation of x (without leading zeroes) equal to n , or −1−1 if it is impossible.
初步思路:
因为是让X变成N位数,而X数位上最大的数<=9,所以X*X数位上最大的数的积,最大为(X的位数+1)位的数,所以,可不可应用贪心呢?
我们来试一下,每轮取X每一位中最大的那一位,设他为Y,则将X*Y,比较位数,用一个CNT计数就行了,看看样例符不符合我们的猜想。
但是,我们无法判断如果X变不成N位数,只得先写代码,后面在思考了!
#include <bits/stdc++.h>//万能头文件
#define long long int //题目中给的是longlong
using namespace std;
int n;//n位数
int x;//原来的数
int getlength(int a){
int length=0;
while(a>0){
length++;
a/=10;
}
return length;
}
int getmax(int a){
int maxv=-1;
int b;
while(a>0){
b=a%10;
a/=10;
maxv=max(maxv,b);
}
return maxv;
}
signed main(){
cin>>n;
cin>>x;
int opt=0;//操作次数
while(getlength(x)<n){
int y=getmax(x);
x=x*y;
opt++;
}
cout<<opt<<endl;
return 0;
}
但是貌似不太行~~~
只能用搜索了!(恍然大悟)
但是——因为开不了10^19的数组,还是不行!
#include <bits/stdc++.h>
using namespace std;
int n,x;
queue<int> q;
int d[20];
int getsize(int a){
int size=0;
while(a>0){
size++;
a/=10;
}
return size;
}
int main(){
cin>>n>>x;
memset(d,-1,sizeof(d));
d[getsize(x)]=0;
q.push(x);
while(!q.empty()){
int f=q.front();
q.pop();
int z=f;
for(int i=1;i<=getsize(x);i++){
int y=z%10;
z/=10;
if(d[getsize(f*y)]==-1){
d[getsize(f*y)]=d[getsize(f)]+1;
q.push(f*y);
}
}
}
cout<<d[n]<<endl;
return 0;
}
只得看题解
额……
最后写了一个还是WA
//可能会MLE的BFS
#include <bits/stdc++.h>
using namespace std;
int n,x;
queue<int> q;
signed d[100000005];
string to_string(int a){
string s;
while(a>0){
s+=(a%10+'0');
a/=10;
}
return s;
}
int main(){
cin>>n>>x;
memset(d,-1,sizeof(d));
q.push(x);
while(!q.empty()){
int f=q.front();
q.pop();
string s=to_string(f);
for(int i=0;i<s.size();i++){
if(s[i]!=0){
int y=f*(s[i]-'0');
if(d[y]==-1){
d[y]=d[f]+1;
q.push(y);
}
}
}
}
sort(d+(1<<n),d+(1<<(n+1))-1);
cout<<d[1<<(n+1)-1]<<endl;
return 0;
}
不玩了……
见续集