UVA - 1341 Different Digits (同余)

Description

Given a positive integer n, your task is to find a positive integerm, which is a multiple of n, and thatm contains the least number of different digits when represented in decimal. For example, number 1334 contains three different digits 1, 3 and 4.

Input 

The input consists of no more than 50 test cases. Each test case has only one line, which contains a positive integern ( 1n < 65536). There are no blank lines between cases. A line with a single `0' terminates the input.

Output 

For each test case, you should output one line, which contains m. If there are several possible results, you should output the smallest one. Do not output blank lines between cases.

Sample Input 

7 
15 
16 
101 
0

Sample Output 

7 
555 
16 
1111
题意:输入正整数n,求它的最小倍数m,使得m包含的不同的数字的种类是最少的,如果有多解,m应该是最小的
思路:首先明确一个证明:对于任意的整数n,必然存在一个由不多于两个的数来组成的一个倍数。然后我们可以先找用一种数能组成的
结果,没有的话,再找两个数组成的结果,在BFS的时候,同样的要用到同余来剪枝。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
const int maxn = 70000;
const int inf = 0x3f3f3f3f;

struct Node {
	int m, step, pre, d;
} q[maxn];
int n, len, ansm, save[5], vis[maxn];
string ans, tmp;

void gettmp(int u) {
	if (u == -1)
		return;
	gettmp(q[u].pre);
	tmp += q[u].d + '0';
}

void bfs() {
	memset(vis, 0, sizeof(vis));
	int head = 0, tail = 0;
	for (int i = 1; i <= len; i++) {
		if (save[i] == 0)
			continue;
		Node cur;
		cur.pre = -1;
		cur.d = save[i];
		cur.m = save[i] % n;
		cur.step = 1;
		vis[cur.m] = 1;
		q[tail++] = cur;
	}

	while (head < tail) {
		int h = head;
		head++;
		if (q[h].step > ansm)
			return;
		if (q[h].m == 0) {
			tmp = "";
			gettmp(h);
			if (q[h].step < ansm) {
				ans = tmp;
				ansm = q[h].step;
			}
			else if (q[h].step == ansm) {
				if (tmp < ans)
					ans = tmp;
			}
			return;
		}

		for (int i = 1; i <= len; i++) {
			int t = (q[h].m * 10 + save[i]) % n;
			if (vis[t])
				continue;
			vis[t] = 1;
			Node tmp;
			tmp.m = t, tmp.step = q[h].step + 1;
			tmp.d = save[i], tmp.pre = h;
			q[tail++] = tmp;
		}
	}
}

int main() {
	while (scanf("%d", &n) != EOF && n) {
		len = 1, ansm = inf;
		for (int i = 1; i <= 9; i++) {
			save[1] = i;
			bfs();
		}
		if (ansm != inf) {
			cout << ans << endl;
			continue;
		}
		len  = 2;
		for (int i = 0; i <= 9; i++) {
			save[1] = i;
			for (int j = i+1; j <= 9; j++) {
				save[2] = j;
				bfs();
			}
		}
		cout << ans << endl;
	}	
	return 0;
}


你可能感兴趣的:(UVA - 1341 Different Digits (同余))