poj 1426 同余 + Bfs

一看就是我不会的题哦吼。。。。默默找了题解
发现了一个神奇的式子:
如果 m%n = r
则 (m * 10 + y ) %n == (r * 10 + y ) % n
发现啥没有? 就是在你加一位的时候你不用一整串再除!!!而是利用余数!!!可以安心地和高精度说再见咯嘿嘿
还有一点要注意,余数一样咱们就别再走一遍咯所以小标记一下
BFS套路:
1.初始化某个东西,扔进去队列
2. 判断队列为空
{
扔出来一个。。。。
3.末条件判断;
4.方向走路
5.范围判断
{
可行扔进去。。。
}
}
代码如下

#include <iostream> 
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <string>
using namespace std;
struct stu{
	string s;
	int left;
};

void bfs (  int n )
{
	int f[205]={0};//表示试过的余数 
	stu be,nex,kk;
	be.s  = "1";
	be.left = 1%n;  f[1%n] = 1; //第一步初始化 
	queue < stu > q;
	q.push(be);
	while ( !q.empty())
	{
		be = q.front();
		q.pop();
		if( be.left == 0) // 末条件 
		{
			cout<<be.s<<endl;
			break;
		 } 
		//1
		nex.s = be.s + "1";
		nex.left = (be.left*10+1) % n;
		if ( !f[nex.left] )
		{
			f[nex.left] = 1;
			q.push(nex);
		 }
		//0
		nex.s = be.s + "0";
		nex.left = (be.left*10+0) % n;
		if ( !f[nex.left] )
		{
			f[nex.left] = 1;
			q.push(nex);
		 } 
		
	 } 
	
}
int main()
{
	int n;
	while ( ~scanf("%d",&n) && n)
	{
		bfs(n);
	}
	return 0;
}
 
发布了55 篇原创文章 · 获赞 1 · 访问量 2633

猜你喜欢

转载自blog.csdn.net/qq_37548017/article/details/105385986