【题目大意】:给你一个数n,以及m个数字,找一个最小的n的倍数,使得这个数仅由m个数字中的任意个组成。
【解题思路】:易知,a%n=x (a*10+b)%n=(x*10+b)%n。然后bfs扫过去就可以了,注意记录余数,和余数的判重。
poj要手写queue才能过,不知道为什么
【代码】:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>
using namespace std;
#define eps 1e-8
#define pi acos(-1.0)
#define inf 1<<30
#define linf 1LL<<60
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long
struct Node{
string num;
int mod;
Node(){}
Node(string a,int b){
num=a,mod=b;
}
};
int n,m;
int a[20];
int vis[6000];
string ans;
bool solve_bfs(){
queue<Node> que;
que.push(Node("",0));
memset(vis,0,sizeof(vis));
while (!que.empty()){
Node p=que.front();
que.pop();
for (int i=0; i<m; i++){
Node tmp;
tmp.num=p.num+(char)('0'+a[i]);
tmp.mod=(p.mod*10+a[i])%n;
if (tmp.num!="0" && tmp.mod==0) {ans=tmp.num; return true;}
if (vis[tmp.mod]==0 && tmp.num!="0") {
que.push(tmp);
vis[tmp.mod]=1;
}
}
}
return false;
}
int main() {
while (~scanf("%d",&n)){
scanf("%d",&m);
for (int i=0; i<m; i++){
scanf("%d",&a[i]);
}
sort(a,a+m);
if (n==0) cout << 0 << endl;
else if (solve_bfs()) cout << ans << endl;
else cout << 0 << endl;
}
return 0;
}
本文介绍了一种使用广度优先搜索(BFS)算法解决特定数学问题的方法:给定一个整数n和一组数字,寻找由这组数字组成的最小的n的倍数。通过BFS遍历所有可能的数字组合,利用模运算进行优化,最终找到符合条件的最小倍数。
&spm=1001.2101.3001.5002&articleId=7419048&d=1&t=3&u=58090a55e4da433f9f003a0a64a4b46c)
1449

被折叠的 条评论
为什么被折叠?



