您的位置:首页 > 其它

暴力dfs POJ1426

2013-07-02 21:38 134 查看
/*

题目地址:http://poj.org/problem?id=1426点击打开链接

题目大意:找出仅用0和1 组成的十进制的数构成是出入n的倍数(n<=200)

解题思路:有人直接打表打了200个,因为并不像想的那样数据那么大,有的直接用数学原理。

当然我用了dfs深搜从第一位1开始往下搜,而且是暴力搜索。。。

*/

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int p,pos;
char res[102];

int dfs(int step,int a)
{
if(step>100)
return 0;        //return 0,则回溯,继续。

if(a%p==0&&step>=0&&step<=100)
{
res[++pos]='\0';
return 1;
}
else
{
pos++;
res[pos]='0';
if(dfs(step+1,(a*10+0)%p))
return 1;     //return 1,则结束。
pos--;
pos++;           //pos++,--来控制res数组保存的值。
res[pos]='1';
if(dfs(step+1,(a*10+1)%p))
return 1;
pos--;
return 0;        //必须回溯
}
}

int main()
{
while(cin>>p&&p)
{
pos=-1;
res[++pos]='1';
dfs(1,1);
cout<<res<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: