Small Multiple 双端队列

6616: Small Multiple

时间限制: 1 Sec  内存限制: 512 MB
提交: 452  解决: 92
[提交] [状态] [讨论版] [命题人:admin]

题目描述

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 is given from Standard Input in the following format:
K

输出

Print the smallest possible sum of the digits in the decimal notation of a positive multiple of K.

扫描二维码关注公众号,回复: 2704502 查看本文章

样例输入

6

样例输出

3

提示

12=6×2 yields the smallest sum.

求数n的倍数中数位和最小的和

队数n的操作有两种方式

1. n+1  数位和加一(不考虑9的情况,因为9加一所能达到的状态可以直接通过1*10来获得,而*10这种方式得到的数位和还不会增加)

2. n*10 数位和不变

考虑用双端队列来维护

从起始数字为1开始,方式一得到的从队列后端插入,方式二得到的从队列前端加入,这样也保证数位和是不递减的

同时用一个vis来标记该数是否出现过,若vis[n]为0,则表明该数%k是第一次出现,并且该数最小,即数位和最小

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxx=1e5+100;
const int MOD=1e9;
const int INF=1e9;
struct node
{
    int p,v;
}temp;
int vis[maxx];
int main()
{
    int n;
    cin>>n;
    deque<node> q;
    memset(vis,0,sizeof(vis));
    q.push_front((node){1,1});
    while(!q.empty()){
        temp=q.front();
        q.pop_front();
        if(vis[temp.p])  continue;
        vis[temp.p]=1;
        if(temp.p==0){
            cout<<temp.v<<endl;
            break;
        }
        q.push_front((node){temp.p*10%n,temp.v});
        q.push_back((node){(temp.p+1)%n,temp.v+1});
    }
    return 0;
}

网上正解应该是求最短路,但是这个方法不太理解,而且SPFA还没系统学习过,以后再补这个思路

猜你喜欢

转载自blog.csdn.net/renzijing/article/details/81504179