您的位置:首页 > 其它

zoj 1136 Multiple(数学+bfs)

2012-04-01 13:44 441 查看
【题目大意】:给你一个数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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: