1. 程式人生 > >【BFS】【余數剪枝】Multiple

【BFS】【余數剪枝】Multiple

wid def ever ems 如何 decimal following exists ota

[poj1465]Multiple
Time Limit: 1000MS Memory Limit: 32768K
Total Submissions: 7731 Accepted: 1723

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

題目大意:給你一個在0至4999之間的數N,在給你M個數,輸出這些數能組成的最小的N的倍數,沒有輸出0

試題分析:本體盲目搜是不可取的,因為我們根本就不知道要搜到哪裏(對於DFS),每個數的數量可以取無限多個……

那麽對於BFS來說數量還是比較多,但BFS擅長解決一些沒有邊界的問題嘛,所以用BFS解決此題

那麽如何剪枝呢?

對於一個數(AX+Y)%X與(BX+Y)%X的余數是一樣的,至於取誰,小的那個(也就是先搜到的那個)是我們要的,大的可以直接剪掉,所以只需要開一個數組Hash一下就好了……

註意特判N=0的情況!!!

代碼

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
//#include<cmath>

using namespace std;
const int INF = 9999999;
#define LL long long

inline int read(){
	int 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;
}
int N,M;
int a[5101];
int l=1,r=1;
bool flag[5101];
bool fla=false;
struct data{
	int ga,last,ans;
}Que[5101]; 
void print(data k){
	if(k.ga!=-1){
		print(Que[k.ga]);
		printf("%d",k.ans);
	}
} 
void BFS(){//a當前數字 
	Que[1].last=0; 
	Que[1].ans=0;
	Que[1].ga=-1; 
	int l1,p;
	while(l<=r){
		l1=Que[l].last;
		for(int i=1;i<=M;i++){
			p=(l1*10+a[i])%N;
			if(!flag[p]&&(Que[l].ga!=-1||a[i]>0)){
				flag[p]=true;
				Que[++r].ans=a[i];
				Que[r].ga=l;
				Que[r].last=p;
				if(p==0){
					data s=Que[r];
					print(s);
					printf("\n");
					fla=true;
					return ;
				}
			}
		}
		l++;
	}
}
int main(){
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	while(scanf("%d",&N)!=EOF){
		M=read();
		for(int i=1;i<=M;i++) a[i]=read();
		sort(a+1,a+M+1);
		if(N==0){
			puts("0");
			continue;
		}
		memset(flag,false,sizeof(flag));
		l=r=1;
		fla=false;
		BFS();
		if(!fla){
			puts("0");
		}
	}
	return 0;
}

【BFS】【余數剪枝】Multiple