1109 01组成的N的倍数

Problem

给定一个自然数N,找出一个M,使得M > 0且M是N的倍数,并且M的10进制表示只包含0或1。求最小的M。
例如:N = 4,M = 100。

Solution

bfs,有点难写。

Code

#include<stdio.h>
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n;
struct E{
	int cur,cnt;
	vector<int>v;
	E(int cu,int cn):cur(cu),cnt(cn){}
};
bool check(int x){
	while(x){
		if(x%10!=0&&x%10!=1){
			return false;
			
		}
		x/=10;
	}
	return true;
}
int sum=10000;
vector<int>ans;
queue<E>q;
vector<int>minn(vector<int> &x,vector<int> &y){
	if(x.size()>y.size()) return y;
	if(x.size()<y.size()) return x;
	for(int i=x.size()-1;i>=0;i--){
		if(x[i]>y[i]){
			return y;
		}
		else if(x[i]<y[i]){
			return x;
		}
	}
	return y;
}
void bfs(){
	if(check(n)){
		sum=1;
		while(n){
			ans.push_back(n%10);
			n/=10;
		}
		return;
	}
	q.push(E(0,0));
	while(!q.empty()){
		E cur=q.front();q.pop();
		if(cur.cnt+1>sum) return;
		for(int i=0;i<=9;i++){
			E nex=cur;
			nex.cur=cur.cur+i*n;
			nex.cnt++;
			if(nex.cur%10==0||nex.cur%10==1){
				nex.v.push_back(nex.cur%10);
				nex.cur/=10;
				if(check(nex.cur)&&i!=0){
					while(nex.cur){
						nex.v.push_back(nex.cur%10);
						nex.cur/=10;
					}
					if(sum==10000){
						ans=nex.v;
						sum=nex.cnt;
						/*for(int i=nex.v.size()-1;i>=0;i--){
							printf("%d",nex.v[i]);
						}
						printf("
");*/
					}
					else{
						ans=minn(ans,nex.v);
						/*for(int i=nex.v.size()-1;i>=0;i--){
							printf("%d",nex.v[i]);
						}
						printf("
");*/
					}
				}
				else{
					q.push(nex);
				}
			}
		}
	}
}
int main(){
	scanf("%d",&n);
	bfs();
	for(int i=ans.size()-1;i>=0;i--){
		printf("%d",ans[i]);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/sz-wcc/p/12952444.html