1. 程式人生 > >POJ 1426 Find The Multiple(大數取模)【DFS】||【BFS】

POJ 1426 Find The Multiple(大數取模)【DFS】||【BFS】

++ printf true pty ace bfs 還要 ems 兩種

<題目鏈接>

題目大意:

給一個小於200的正整數n,問只有0和1組成的位數小於100的最小能被n整除的數是多少。

解題分析:

用DFS或者BFS沿著位數進行搜索,每一次搜索到下一位都有兩種情況,0或者1,還要註意的是,大數取模的方法。但是我有一個疑問,這題位數最高為100,用dfs為什麽不會超時?還是說只是此題數據太弱嗎?

BFS解法

#include<iostream>
#include<cstdio>
#include<queue>
#include<string>
#include<algorithm>
using namespace
std; inline bool big_mod(string &s,int mod) //大數取模運算 { int ans=0; for( int i=0;i<s.size();i++) { ans=(ans*10+s[i]-0)%mod; } return ans==0; } string bfs(int n) { queue<string>q; q.push("1"); //首位一定為1 while(!q.empty()) { string top=q.front(); q.pop();
if(big_mod(top,n)) //如果該數能被n整除,則符合 { return top; } for(int i=0;i<2;i++) { string temp=top+char(0+i); if(big_mod(temp,n)) { return temp; } q.push(temp); } } } int main() {
int n; while(~scanf("%d",&n)&&n) { cout<<bfs(n)<<endl; } return 0; }

DFS解法

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;

bool flag;
char s[110];

void dfs(int mod,int d,int n)
{
    if(d>100) return ;
    if(mod==0)
    {
        flag=true;
        s[d]=0;
        return ;
    }
    if(!flag)
    {
        s[d]=0;
        dfs((mod*10)%n,d+1,n);   
    }
    if(!flag){
        s[d]=1;
        dfs((mod*10+1)%n,d+1,n); 
    }
}

int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        if(n==0) break;
        memset(s,0,sizeof(0));
        s[0]=1;        //首位為1
        flag=false;
        dfs(1,1,n);
        printf("%s\n",s);
    }
    return 0;
}

2018-08-28

POJ 1426 Find The Multiple(大數取模)【DFS】||【BFS】