1. 程式人生 > >POJ 1426 Find The Multiple(kuangbin帶你飛 專題一:簡單搜尋)

POJ 1426 Find The Multiple(kuangbin帶你飛 專題一:簡單搜尋)

題意:給定一個n,找一個能被n整除並且每一位都是0或者1的數字...

簡單bfs,第一位肯定是1,然後求得餘數,後面添一個0或者1的時候將當前餘數*10+0或者1....找到倍數後將字串後面補個‘\0’puts輸出就好了...

#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<queue>
#include<iostream>
using namespace std;
int used[233],n;
struct node
{
    char s[110];//當前數字串
    int x,t;//x為餘數,t為當前位數
};
void bfs()
{
    queue<node> q;
    memset(used,0,sizeof(used));
    used[1]=1;
    node  now,next;
    now.s[0]='1';
    now.x=1%n,now.t=1;
    q.push(now);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        if(now.x==0)
        {
            now.s[now.t]='\0';
            puts(now.s);
            return ;
        }
        next.x=(now.x*10)%n;
        strcpy(next.s,now.s);
        next.s[now.t]='0';
        next.t=now.t+1;
        if(!used[next.x])
        {
            used[next.x]=1;
            q.push(next);
        }
        next.x=(now.x*10+1)%n;
        strcpy(next.s,now.s);
        next.s[now.t]='1';
        next.t=now.t+1;
        if(!used[next.x])
        {
            used[next.x]=1;
            q.push(next);
        }
    }
}
int main()
{
    while(cin>>n,n)
    {
        bfs();
    }
    return 0;
}