码迷,mamicode.com
首页 > 其他好文 > 详细

ZOJ 1136 Multiple (BFS)

时间:2015-08-11 06:50:32      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

Multiple

Time Limit: 10 Seconds      Memory Limit: 32768 KB

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的倍数。

思路:bfs 输出的时候相当于遍历路径一边,所以有pre.

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <set>
using namespace std;

const int INF=0x3f3f3f3f;
const double eps=1e-10;
const double PI=acos(-1.0);
#define maxn 5000

struct Node
{
    int num, pre, id, yu;
};
Node node[maxn];
int vis[maxn];
int n, m;
int a[maxn];
void output(int id)
{
    if(node[id].pre == -1)
        return;
    output(node[id].pre);
    printf("%d", node[id].num);
}
void bfs()
{
    memset(vis, 0, sizeof vis);
    node[0].id = 0;
    node[0].pre = -1;
    node[0].yu = 0;
    int cnt = 1;
    queue<int> q;
    q.push(0);
    while(!q.empty())
    {
        int id = q.front();
        q.pop();
        for(int i = 0; i < m; i++)
        {
            if(node[id].yu == 0 && a[i] == 0)
                continue;
            int yu = (node[id].yu*10+ a[i])%n;
            if(!vis[yu])
            {
                if(yu == 0)
                {
                    output(id);
                    printf("%d\n", a[i]);
                    return;
                }
                vis[yu] = 1;
                node[cnt].pre = id;
                node[cnt].num = a[i];
                node[cnt].yu = yu;
                node[cnt].id = cnt;
                q.push(cnt++);
            }
        }
    }
    printf("%d\n", 0);
}
int main()
{
    while(~scanf("%d",&n))
    {
        scanf("%d", &m);
        for(int i = 0; i < m; i++) scanf("%d", &a[i]);
        sort(a, a + m);
        if(n == 0)
            printf("%d\n", 0);
        else
            bfs();
    }
    return 0;
}

 

ZOJ 1136 Multiple (BFS)

标签:

原文地址:http://www.cnblogs.com/ZP-Better/p/4719675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!