首页 > 其他分享 >D. Required Length

D. Required Length

时间:2022-11-19 20:58:16浏览次数:58  
标签:10 cnt cout getlen int Required Length mp

D. Required Length

题意:给你一个长度n,一个数x,x每个后续状态可以由前一个状态乘以前一个状态的某一位上的数字得到,问最少多少步,能把x变成一个n位数。如果不能变成n位数,输出-1。

思路:bfs + map。map用来记录第一次到达某个数所要经过的步数,第一次找到的值就是步数的最小值。

#include<bits/stdc++.h>
#define int long long
using namespace std;

int n, x;
map<int,int> mp;

int getlen(int x){
    int cnt = 0;
    while(x > 0){
        x /= 10;
        cnt ++;
    }
    return cnt;
}

inline set<int> getdigit(int x){
    set<int> s;
    while(x > 0){
        if(x % 10 != 0){
            s.insert(x % 10);
        }
        x = x / 10;
    }
    return s;
}

signed main(){
    cin >> n >> x;
    if(getlen(x) == n){
        cout << 0 << endl;
        return 0;
    }
    else if(getlen(x) > n){
        cout << -1 << endl;
        return 0;
    }
    queue<int> q;
    q.push(x);
    mp[x] = 0;
    while(!q.empty()){
        int u = q.front();
        q.pop();
        if(getlen(u) == n){
            cout << mp[u];
            return 0;
        }
        else if(getlen(u) > n){
            cout << -1;
            return 0;
        }
        set<int> s = getdigit(u);
        for(auto it : s){
            if(!mp.count(it * u)){
                mp[it * u] = mp[u] + 1;
                q.push(it * u);
            }
        }
    }
    
    cout << -1;
    return 0;
}

标签:10,cnt,cout,getlen,int,Required,Length,mp
From: https://www.cnblogs.com/N-lim/p/16907001.html

相关文章