pku 1426 Find The Multiple

额,自己的代码比较水,用普通的方法做的,内存开得太大了

View Code
#include"stdio.h"
#define maxn 11000000
__int64 q[maxn];
int n;
void bfs()
{
int i,j;
__int64 x;
q[
0]=1;
i
=0;j=1;
while(i<j)
{
x
=q[i];
if(x%n==0)
{
printf(
"%I64d\n",x);
break;
}
x
*=10;
q[j
++]=x;
q[j
++]=x+1;
i
++;
}
}

int main()
{
while(scanf("%d",&n)!=EOF&&n!=0)
{
bfs();
}
return 0;
}

看下大牛的代码,做了预处理,中间还加了剪枝,BFS

View Code
#include <iostream>
#include
<queue>
#include
<string>
#include
<CSTDIO>
using namespace std;
string ans[210];
bool mark[210];
struct node
{
string ans;
int mod;
};
string BFS(int n)
{
//memset(mark,0,sizeof(mark));
queue<node>q;
node s;
s.ans
="1";
s.mod
=1;
q.push(s);
mark[
1]=true;
while(!q.empty())
{
node now
=q.front(),temp=now;
q.pop();
int c=(now.mod*10+1)%n;
int d=(now.mod*10)%n;
if(d==0)
{
temp.ans
+="0";
return temp.ans;
}
if(c==0)
{
temp.ans
+="1";
return temp.ans;
}
if(!mark[d])//剪枝
{
mark[d]
=1;
temp.ans
+="0";
temp.mod
=d;
q.push(temp);
}
if(!mark[c])
{
mark[c]
=1;
now.ans
+="1";
now.mod
=c;
q.push(now);
}
}
}
int main()
{
int n;
for(int i=1;i<=5;i++)
{
if(i&1)
ans[i]
=BFS(i);
else
ans[i]
=ans[(i>>1)]+"0";//这步处理比较妙,因为这是special judge,只要是它的倍数即可
}
while (scanf("%d",&n)&&n)
{
cout
<<ans[n]<<endl;
}
}
posted @ 2011-08-03 21:03  枕边梦  阅读(188)  评论(0编辑  收藏  举报