题目;
https://vjudge.net/contest/169035#problem/E
这题初衷是用数论中的同余模定理,但是由于数据比较弱,所以不用也可以过。
先看下标准解法:
https://blog.youkuaiyun.com/lyy289065406/article/details/6647917
(大神写的非常到位)
大神的解释略微复杂,我来解释一下:
(1)
这里的mod[i/2]其实是mod[i]的父节点(二叉树,因为每个节点都有两种可能),不论i是奇数还是偶数。
(2)
i/2是得到这个节点的父节点,i%2是表示判断这个节点是奇数还是偶数,如果是奇数,那么是bfs的第一个入口(bfs 是双入口的形式),则填0,若是偶数,则是第二个入口,那么填1。
(3)
这一步分析写得很精彩,而且是本算法的核心理解,请自行理解。
再看看投机取巧的我的方法:
//5
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
#define MAXN 110
typedef long long LL;
queue<LL>q;
LL bfs(int n)
{
LL now,next;
while(!q.empty())
q.pop();
q.push(1);
while(!q.empty())
{
now=q.front();
q.pop();
if(now%n==0)
return now;
next=now*10;//后接0
if(next%n==0)
return next;
else
q.push(next);
next+=1;//后接1
if(next%n==0)
return next;
else
q.push(next);
}
return -1;
}
int main()
{
int n;
while(scanf("%d",&n)&&n)
printf("%lld\n",bfs(n));
return 0;
}
这题是用long long才可以过(如果不用同余模定理),并不需要像有些人说的用ULL才可以。但是,因为是投机取巧,所以用int会发生溢出。
还有很玄学的是用c++超时的用g++能过。