ZOJ - 1136 Multiple (同餘+BFS)

來源:互聯網
上載者:User

標籤:des   os   io   strong   for   ar   amp   sp   line   

Description

a program that, given a natural number N between 0 and 4999 (inclusively), and M distinct decimal digits X1,X2..XM (at least one), finds the smallest strictly positive multiple of N that has no other digits besides X1,X2..XM (if such a multiple exists).

The input file has several data sets separated by an empty line, each data set having the following format:

On the first line - the number N
On the second line - the number M
On the following M lines - the digits X1,X2..XM.

For each data set, the program should write to standard output on a single line the multiple, if such a multiple exists, and 0 otherwise.

An example of input and output:


Input

22
3
7
0
1

2
1
1


Output

110

0

題意:讓你用m個數組成n的倍數,要求最小

思路:首先我們排序這m個數,然後從高位開始搜,這樣才能保證最先BFS的是最小的,這裡用到了一個剪枝就是對於:餘數相同的,我們可以拿來判重,小的比較優,也就是最先放進隊列的比較優

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>using namespace std;const int maxn = 10005;struct Node {int res;int pre;int digit;} q[maxn];int a[maxn], vis[maxn];int n, m;void print(int u) {if (q[u].pre == -1)return;print(q[u].pre);printf("%d", q[u].digit);}int bfs() {q[0].digit = 0;q[0].pre = -1;q[0].res = 0;memset(vis, 0, sizeof(vis));int front = 0, rear = 1;while (front < rear) {Node tmp = q[front];for (int i = 0; i < m; i++) {int t = (tmp.res * 10 + a[i]) % n;if (a[i] == 0 && tmp.pre == -1)continue;if (!vis[t]) {vis[t] = 1;Node tmp;tmp.digit = a[i];tmp.pre = front;tmp.res = t;q[rear++] = tmp;}if (t == 0) {print(rear-1);printf("\n");return 1;}}front++;}return 0;}int main() {while (scanf("%d%d", &n, &m) != EOF) {for (int i = 0; i < m; i++)scanf("%d", &a[i]);if (n == 0) {printf("0\n");continue;}sort(a, a+m);if (!bfs())printf("0\n");}return 0;}


ZOJ - 1136 Multiple (同餘+BFS)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.