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

HDU 4474(神奇的BFS+强剪枝)

时间:2015-08-26 22:38:09      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:acm


HDU - 4474
Time Limit: 20000MS   Memory Limit: 65536KB   64bit IO Format: %I64d & %I64u

            

Description

There are tons of problems about integer multiples. Despite the fact that the topic is not original, the content is highly challenging. That’s why we call it “Yet Another Multiple Problem”.
In this problem, you’re asked to solve the following question: Given a positive integer n and m decimal digits, what is the minimal positive multiple of n whose decimal notation does not contain any of the given digits?
 

Input

There are several test cases.
For each test case, there are two lines. The first line contains two integers n and m (1 ≤ n ≤ 104). The second line contains m decimal digits separated by spaces.
Input is terminated by EOF.
 

Output

For each test case, output one line “Case X: Y” where X is the test case number (starting from 1) while Y is the minimal multiple satisfying the above-mentioned conditions or “-1” (without quotation marks) in case there does not exist such a multiple.
 

Sample Input

2345 3 7 8 9 100 1 0
 

Sample Output

Case 1: 2345 Case 2: -1
 

Hint

Source

2012 Asia Chengdu Regional Contest

题意:
给出一个数字n,和m个一位数字,求n的最小倍数,使得其中不会出现这m个数字。
思路:
开始想的是暴力枚举一下= = 结果发现根本找不到一个上界,果断弃疗。
其实一个BFS,再加一个优化就可以解决。
同余剪枝:对于每次搜索到的数x, 判断一下 x mod n 是否已经存在。如果存在的话,说明有比当前结果更优的解,直接跳过。直到x mod n == 0,回溯输出ans。

AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int n, m, a[15],mod[10000+5],ans[10000+5],pre[100000+5];
bool flag;
void print(int u)
{
  if(u == -1) return;
  print(pre[u]);
  printf("%d",ans[u]);
  return;
}
void bfs()
{
  queue<int> q;
  for(int i = 1;i < 10;i ++)
  {
    if(!a[i])
	{
	  if(mod[i%n] == 1) continue;
	  q.push(i%n);
	  ans[i%n] = i;
	  mod[i%n] = 1;
	}
  }
  while(!q.empty())
  {
   int u = q.front();
   //cout << u<<endl;
   q.pop();
   if(u == 0)
   {
     flag = 1;
     print(u);
     return;
   }
   for(int i = 0;i < 10;i ++)
   {
	 if(!a[i])
	 {
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~	   
	   int x = (u*10 + i) % n;    //同余剪枝
       if(mod[x] == -1)
	   {
         mod[x] = 1;
	     ans[x] = i;
	     pre[x] = u;
	     q.push(x);    //这里只需要将x放进队列即可
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	   }
	 }
   }
  }
  printf("-1");
}
int main()
{
	int cases = 1;
	while(scanf("%d%d", &n, &m) != EOF)
	{
	  flag = 0;
	  memset(a, 0, sizeof(a));
	  memset(mod,-1,sizeof(mod));
	  memset(pre,-1,sizeof(pre));
	  while(m --)
	  {
	    int x;
	    scanf("%d", &x);
	    a[x] = 1;
	  }
	  printf("Case %d: ",cases ++);
	  bfs();
      printf("\n");
	}
	return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

HDU 4474(神奇的BFS+强剪枝)

标签:acm

原文地址:http://blog.csdn.net/mowenwen_/article/details/48009049

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