Problem Description
Find the smallest possible sum of the digits in the decimal notation of a positive multiple of K.
Constraints
- 2≤K≤105
- K is an integer.
Input
Input is given from Standard Input in the following format:
K
Output
Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.
Example
Sample Input 1
6
Sample Output 1
3
12=6×2 yields the smallest sum.Sample Input 2
41
Sample Output 2
5
11111=41×271 yields the smallest sum.Sample Input 3
79992
Sample Output 3
36
题意:给出一个整数 k,求这个数的倍数,使得其各位数的和最小,并输出这个和
思路:bfs
设答案为 x,由于要求 x 的各位数之和最小,那么可以从 1 开始,当搜索到的第一个值 %k 为 0 即为答案
那么有 2 种入队方式:
- x+1:此时各位数字和比之前的多了一个 1,那么代价是 1
- x*10:此时各位数字和比之前没有改变,那么代价就是 0
因此问题转换为用 bfs 找到满足条件的 x,由于要找各位和最小的,也就是说代价为 0 的首先出队,因此可以使用双端队列,将代价为 0 的放在队首,代价为 1 的放在队尾
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 100000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
int vis[N];
int main() {
int n;
scanf("%d",&n);
deque<pair<int,int> > Q;
Q.push_front(make_pair(1,1));
while(!Q.empty()){
pair<int,int> temp=Q.front();
Q.pop_front();
if(!vis[temp.first]){
vis[temp.first]=true;
if(temp.first==0){
printf("%d\n",temp.second);
break;
}
Q.push_front(make_pair((temp.first*10)%n,temp.second));
Q.push_back(make_pair((temp.first+1)%n,temp.second+1));
}
}
return 0;
}