HDOJ 1664 Different digits

来源:互联网 发布:天刀捏脸数据 女 冰儿 编辑:程序博客网 时间:2024/06/05 06:14
Problem Description
Given a positive integer n, your task is to find a positive integer m, which is a multiple of n, and that m 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 integer n ( 1<=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.

【数论】最多只要两种数字就能满足题目要求
【BFS+余数判重】先找用一种数字的数
图的节点记录用的数字,当前的下标,上一个节点的下标和余数。
防止用string超时,自己维护一个队列,记录上一个节点的下标。

#include<iostream>#include<string>#include<vector>using namespace std;int num;vector<bool> flag;struct node{int cur, len, pre, digit, rmd;node(int c = 0, int p = 0, int d = 0, int r = 0, int l = 0){cur = c;pre = p;digit = d;rmd = r;len = l;}};vector<node> q;string bfs1(){int m = 70000;string result;for (int i = 1; i < 10; i++){for (int j = 0; j < num; j++)flag[j] = false;string s;s += char(i + '0');int r = i % num;while (1){if (s.length() >= m)break;if (r == 0){result = s;m = s.length();}if (flag[r])break;flag[r] = true;s += char(i + '0');r = (10 * r + i) % num;}}return result;}string bfs2(){int m = 70000;int result = -1;string temp;for (int i = 0; i < 10; i++){for (int j = 0; j < 10; j++){for (int k = 0; k < num; k++) flag[k] = false;int head = 0, tail = 0;if (i){q[tail] = node(tail, -1, i, i % num, 1);tail++;flag[i % num] = true;}while (head < tail){node t = q[head];head++;if (t.rmd == 0){if (t.len < m){result = t.cur;m = t.len;temp.clear();int rr = result;while (rr != -1){temp = char(q[rr].digit + '0') + temp;rr = q[rr].pre;}}break;}if (t.len > m) break;int ss = i < j ? i : j;int mm = i < j ? j : i;int r1 = (t.rmd * 10 + ss) % num;int r2 = (t.rmd * 10 + mm) % num;if (!flag[r1]){node n = node(tail, t.cur, ss, (t.rmd * 10 + ss) % num, t.len + 1);q[tail] = n;tail++;flag[r1] = true;}if (!flag[r2]){node n = node(tail, t.cur, mm, (t.rmd * 10 + mm) % num, t.len + 1);q[tail] = n;tail++;flag[r2] = true;}}}}return temp;}int main(){cin >> num;while (num){flag.resize(num);q.resize(num);string s = bfs1();if (s != "")cout << s << endl;else cout << bfs2() << endl;cin >> num;}}


0 0
原创粉丝点击