POJ-1426--Find The Multiple---BFS广搜

来源:互联网 发布:淘宝网渔具店 编辑:程序博客网 时间:2024/05/17 22:12

Description
Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.
Input
The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.
Output
For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.
Sample Input
2
6
19
0
Sample Output
10
100100100100100100
111111111111111111

题意:给一个数n,然后找对应的m,m必须是n的倍数,并且只能有0和1组成。如果有多个答案,那么就随意输出一个。

解题思路:这个题不难,先入队1,然后每次*10 和 *10+1,以此入队,知道找到符合的m为止。

但是WA了四次! 编译器这个东西真的有毒。 一开始用了普通队列,全部用的long long int,但是被调函数里如果返回 long long 型的值,用G++提交就会WA(如果直接在被调函数里输出那么就能AC)。。。于是换成C++提交,结果就是TLE了,普通队列不能用,于是换成从大到xiao排序的优先队列(先优先找大的),这样才能AC。

什么都不说了,代码如下(C++提交的):

#include<iostream>#include<cstring>#include<queue>#include<cstdio>using namespace std;long long int bfs(int m){    priority_queue<int,vector<int>,less<int> >q;    q.push(1);    while(!q.empty())    {        long long int t=q.top();        q.pop();        if(t%m==0)        {            return t;        }        q.push(t*10);        q.push(t*10+1);    }}int main(){    int n;    while(scanf("%d",&n)&&n)    {        long long int ans=bfs(n);        printf("%lld\n",ans);    }}