Small Multiple(最短路)

6616: Small Multiple

时间限制: 1 Sec  内存限制: 512 MB
提交: 345  解决: 28
[提交] [状态] [讨论版] [命题人: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.

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

样例输入

6

样例输出

3

提示

12=6×2 yields the smallest sum.

来源/分类

ABC077&ARC084 

分析:这个题和图论结合起来我也是很服气,但是仔细想想也确实有道理。把数字和数字之间建边,边权对于数字之间的差值。其实建边只要x和x+1建边边权为1,x和x*10建边边权为0。

#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<vector>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<deque>
#include<ctype.h>
#include<map>
#include<set>
#include<stack>
#include<string>
#define INF 0x3f3f3f3f
#define FAST_IO ios::sync_with_stdio(false)
const double PI = acos(-1.0);
const double eps = 1e-6;
const int MAX=1e6+10;
const int mod=1e9+7;
typedef long long ll;
using namespace std;
#define gcd(a,b) __gcd(a,b)
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
inline ll qpow(ll a,ll b){ll r=1,t=a; while(b){if(b&1)r=(r*t)%mod;b>>=1;t=(t*t)%mod;}return r;}
inline ll inv1(ll b){return qpow(b,mod-2);}
inline ll exgcd(ll a,ll b,ll &x,ll &y){if(!b){x=1;y=0;return a;}ll r=exgcd(b,a%b,y,x);y-=(a/b)*x;return r;}
inline ll read(){ll x=0,f=1;char c=getchar();for(;!isdigit(c);c=getchar()) if(c=='-') f=-1;for(;isdigit(c);c=getchar()) x=x*10+c-'0';return x*f;}
//freopen( "in.txt" , "r" , stdin );
//freopen( "data.txt" , "w" , stdout );
struct node
{
    int from, to, w;
} G[MAX];
int dist[MAX];
int head[MAX];
bool vis[MAX];
int cnt;
void add(int u, int v, int w)
{
    G[cnt].to=v;
    G[cnt].w=w;
    G[cnt].from=head[u];
    head[u]=cnt++;
}
int k;
void init()
{
    int i,j;
    memset(vis,0,sizeof(vis));
    memset(head,-1,sizeof(head));
    fill(dist,dist+MAX,100000);

    scanf("%d",&k);
    for(i=0;i<k;i++)
    {
        int a=i;
        int b=(i+1)%k;
        int c=i*10%k;

        add(a,b,1);
        add(a,c,0);
    }
}

void spfa(int s)
{
    memset(vis, false, sizeof(vis));
    queue<int> q;
    while(!q.empty())
        q.pop();
    vis[1]=true;
    q.push(s);
    dist[s]=0;
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        vis[u]=false;
        for(int i=head[u]; ~i; i=G[i].from)
        {
            int v=G[i].to;
            if(dist[v]>dist[u]+G[i].w)
            {
                dist[v]=dist[u]+G[i].w;
                if(!vis[v])
                {
                    vis[v]=true;
                    q.push(v);
                }
            }
        }
    }
}

void output()
{
    printf("%d\n",dist[0]+1);
}
int main()
{
    init();
    spfa(1);
    output();

    return 0;
}





猜你喜欢

转载自blog.csdn.net/ToBeYours/article/details/81393402