CA Academy 0-K Multiple [bfs,记录路径]【思维建图】

来源:互联网 发布:ubuntu 用户管理 编辑:程序博客网 时间:2024/06/07 09:05

题目链接:https://csacademy.com/contest/archive/task/0-k-multiple/solution/

————————————————————————————————————————

0-K Multiple
Time limit: 1000 ms
Memory limit: 128 MB

You are given an integer N and a digit K. Find the smallest multiple of N that consists only of digits K and 0.

Standard input
The first line contains two integers NN and KK.

Standard output
Print the result on a single line.

Constraints and notes
1N105,1K9

Input
5 2
Output
20

Input
7 4
Output
4004

Input
13 7
Output
7007
————————————————————————————————————————

题意:
给你一个数N和一个数字K

让你找到一个最小的有K和0组成的数字,能被N整除


解题思路:

对于这个数字能确定第一位一定是K,
有了下一位 就是K*10+0/K了,

这种操作下出现的所有数字对N取模依然会有一个结果,且不超过N的.且最后一定有一个是%N为0的.这种情况就是答案了,

所以我们可以的枚举K*10+0/K这样的数来计算,但是注意题目要求的是最小的,

这时候有 我们可以类似于建立一个有向图

这里写图片描述

然后bfs下去就好了,先处理0,在处理k,这样到达每个%N的位置均能保证最小,然后处理一个数组记录下路径就好了

附本题代码
————————————————————————————————————

int n,k;int d[N],f[N],c[N];int main(){    while(cin>>n>>k){        for(int i=0;i<=n;i++) d[i]=INF;        queue<int>q;        q.push(k%n);        d[k%n]=1;        c[k%n]=k;        f[k%n]=-1;        while(!q.empty()){            int t = q.front();q.pop();            int tem = (t*10)%n;            int tmp = (t*10+k)%n;            if(d[tem]==INF){                d[tem]=d[t]+1;                c[tem]=0;                f[tem]=t;                q.push(tem);            }            if(d[tmp]==INF){                d[tmp]=d[t]+1;                c[tmp]=k;                f[tmp]=t;                q.push(tmp);            }        }        string s = "";        int x = 0;        while(x>=0){            s+=(char)('0'+c[x]);            x=f[x];        }        reverse(s.begin(),s.end());        cout << s<< "\n";    }    return 0;}