UVA - 1341 Different Digits (同余)

Description

Download as PDF

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 ( 1$ \le$n < 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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值