Multiple POJ - 1465 (congruential pruning)

Multiple

Title link: POJ - 1465
title meaning: Given a decimal number n, and m decimal digits, find a minimum number x, such that x is a multiple of n, output n;
a new knowledge point: congruence cut Branch;
we first sort the m decimal digits from small to large. When a<b, if a≡b(mod n), we will no longer expand b (a is small, so we expand a first),
why? Since a and b are congruent to n, (a*10+i)%n == (b*10+i)%n;, when adding an i after b can divide n, a must also add i before b Divide n; it can also be said that the expansion of b must be expanded by a, so there is no need to expand b; (we require a minimum value!!!)
Note that when n=0, a special judgment is required;
because the final result may be a Large numbers, so find a clever way to store numbers; see the code for details;
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int INF = 0x3f3f3f3f;
int digit[15], n, m;
struct node{//now indicates what number is in the current digit, pre indicates what number is in the previous digit, mod indicates the remainder of the current number to n;
	int now, pre, mod;
};
int force[5100];
vector<node> vec;
vector<int> ans;
void print(int k){
	ans.clear();
	while(k>=0){
		ans.push_back(vec[k].now);
		k = vec [k] .pre;
	}
	for(int i=ans.size()-1; i>=0; i--){
		printf("%d", ans[i]);
	}
	printf("\n");
}
void bfs(){
	vec.clear();
	node tmp;
	memset(vis, 0, sizeof(vis));
	for(int i=0; i<m; i++){
		if(digit[i]==0) continue;//Cannot have leading zeros; because 0mod any number is 0;
		tmp.now=digit[i];
		tmp.pre=-1;
		tmp.mod=digit[i]%n;
		show [tmp.mod] = 1;
		vec.push_back(tmp);
	}
	int head=0;
	while(head<vec.size()){
		tmp=vec[head];
		//printf("%d %d %d\n", tmp.now, tmp.mod, tmp.pre);
		if(tmp.mod==0){
			print(head);
			return;
		}
		for(int i=0; i<m; i++){
			int tmod=(tmp.mod*10+digit[i])%n;
			if(vis[tmod]) continue;
			node p;
			p.now=digit[i];
			p.pre=head;
			p.mod = tmod;
			vec.push_back(p);
			show [tmod] = 1;
		}
		head++;
	}
	printf("0\n");
}
int main(){
	while(~scanf("%d%d", &n, &m)){
		for(int i=0; i<m; i++)
			scanf("%d", &digit[i]);
		sort(digit, digit+m);
		if(n==0){
			printf("0\n");
			continue;
		}
		bfs();
	}
	return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325782557&siteId=291194637