URAL1495搜索_背包?

本文解析了一道算法题目,任务是寻找给定整数n的最小倍数sum,要求sum的每位数字只能是1或2。文章通过示例说明了如何使用BFS搜索策略解决该问题,并给出了具体的C++实现代码。

1495. One-two, One-two 2

Time limit: 2.0 second

Memory limit: 64 MB

A year ago the famous gangster Vito Maretti woke up in the morning and realized that he was bored of robbing banks of round sums. And for the last year he has been taking from banks sums that have only digits 1 and 2 in their decimal notation. After each robbery, Vito divides the money between N members of his gang. Your task is to determine the minimal stolen sum which is a multiple of N.

Input
The input contains the number N (1 ≤ N ≤ 106).

Output
Output the minimal number which is a multiple of N and whose decimal notation contains only digits 1 and 2. If it contains more than 30 digits or if there are no such numbers, then output "Impossible".

Samples

input:5

output:
Impossible

Input:8

Output:112

题意
给定一个整数n,求n的倍数sum,要求sum的每一位都是1或者2,sum应是最小的,sum不存在或者位数超过30位时输出Impossible
解法
一个公式: (a*b)%c = (a%c)*(b%c)%c
bfs搜索,从低位开始搜索,范围限定在0到 n-1 , 用string记录每个结果,每个结果对应着一个%n的值,如果这个值=0 那么这个就是最终结果
一开始竟然从先搜索低位!还调了半天+ + 迷
据说可以用背包的思想解,后续补坑。。。
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,string>P;
const int maxn = 1e6+10;
int vis[maxn];
char x[]="012";
int n;
string bfs()
{
    queue<P>q;
    q.push(P(0,""));
    while(!q.empty())
    {
        string now = q.front().second;
        int num = q.front().first;
        q.pop();
        for(int i=1;i<=2;i++)
        {
            int mid = (num*10+i)%n;
            if(mid ==0) return now+x[i];
            if(!vis[mid]&&now.size()<30) q.push(P(mid,now+x[i]));
            vis[mid]=1;
        }
    }
    return " ";
}

int main()
{
    while(cin>>n){
        memset(dp,0,sizeof(dp));
        memset(vis,0,sizeof(vis));
        string fin=bfs();
        if(fin!=" ")cout<<fin<<endl;
        else cout<<"Impossible"<<endl;
    }
    return 0;
}

转载于:https://www.cnblogs.com/star-and-me/p/8878043.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值