您的位置:首页 > 其它

TOJ 3031 Multiple

2014-02-24 12:38 253 查看
Description

a program that, given a natural number N between 0 and 4999 (inclusively), and M distinct decimal digits X1,X2..XM (at least one), finds the smallest strictly positive multiple of N that has no other digits besides X1,X2..XM (if such a multiple exists).

Input

The input has several data sets separated by an empty line, each data set having the following format:

On the first line - the number N
On the second line - the number M
On the following M lines - the digits X1,X2..XM.

Output

For
each data set, the program should write to standard output on a single
line the multiple, if such a multiple exists, and 0 otherwise.

An example of input and output:

Sample Input

22
3
7
0
1

2
1
1

Sample Output

110
0

Source

Southeastern Europe 2000

组队训练赛的一题,智商捉鸡。压根没头绪。看了别人的思路说是用广搜分别枚举每一位然后除以n是否模得0。

还有过程中可以对余数重复剪掉。

代码重新写了一遍。

#include <stdio.h>
#include <queue>
#include <iostream>
using namespace std;

int n,m;
int M[101];
bool visited[6000];

struct Node{
int digit;
int pre;
int mod;
int cnt;
}nod[6000];

int bfs(){
queue<int> Q;
memset(visited,0,sizeof(visited));
int cur=0;
nod[cur].digit=0;
nod[cur].pre=-1;
nod[cur].mod=0;
nod[cur].cnt=cur;
Q.push(cur++);
while( !Q.empty() ){
int now=Q.front();
int now_mod;
Q.pop();
for(int i=0; i<m; i++){
if(nod[now].mod==0 && M[i]==0)continue;
now_mod=(nod[now].mod*10+M[i])%n;
if( !visited[now_mod] ){
visited[now_mod]=1;
if(now_mod==0){
int r[6000];
int index=0;
r[index++]=M[i];
while( nod[now].pre!=-1 ){
r[index++]=nod[now].digit;
now=nod[now].pre;
}
for(int i=index-1; i>=0; i--){
printf("%d",r[i]);
}
printf("\n");
return 1;
}else{
nod[cur].digit=M[i];
nod[cur].pre=nod[now].cnt;
nod[cur].mod=now_mod;
nod[cur].cnt=cur;
Q.push(cur++);
}
}
}
}
return 0;
}

int main(int argc, char *argv[])
{
while( scanf("%d",&n)!=EOF ){
scanf("%d",&m);
for(int i=0; i<m; i++){
scanf("%d",&M[i]);
}
sort(M,M+m);
if( n==0 || !bfs() ){
puts("0");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: