Number_纪中1781_bfs+hash

Description

  给出一个整数 ,你可以对 进行两种操作。
  1、将x变成4x+3
  2、将x变成8x+7
  问,最少通过多少次操作,使得x是1000000007的倍数?

Input

  一行,一个整数x(1<=x<=1000000006)。

Output

  一行,表示最少的操作步数。保证答案不超过10^5。

Hint

[数据约定]

对于50%的数据,答案不超过10
对于80%的数据,答案不超过1000
对于100%的数据,答案不超过100000

题解

想到bfs,看了看状态可能会重复所以加了hash判重

结果他们说有规律可循,微醺

code

const
  p=1000000007;
  maxn=1000000;
var
  s:array[1..maxn]of int64;
  t:array[1..maxn]of longint;
  h:array[0..403219]of longint;
  n:int64;
function hash(x:longint):longint;
var
  i:longint;
begin
  i:=x mod 403219;
  while (h[i]<>0)and(h[i]<>x) do
  i:=(i mod 403219)+1;
  hash:=i;
end;
procedure bfs;
var
  head,tail:longint;
  i:int64;
begin
  s[1]:=n;
  head:=0;
  tail:=1;
  repeat
    head:=(head+1);
    i:=(s[head]*4 mod p+3)mod p;
    if (h[hash(i)]<>i)or(i=0) then
    begin
      h[hash(i)]:=i;
      tail:=(tail+1);
      s[tail]:=i;
      t[tail]:=t[head]+1;
    end;

    i:=(s[head]*8 mod p+7)mod p;
    if (h[hash(i)]<>i)or(i=0) then
    begin
      h[hash(i)]:=i;
      tail:=(tail+1);
      s[tail]:=i;
      t[tail]:=t[head]+1;
    end;
  until (head>=tail)or(s[head]=0)or(s[tail]=0)or(t[head]>100000);
  if s[head]=0 then
  writeln(t[head])
  else
  if s[tail]=0 then
  writeln(t[tail]);
end;
begin
  readln(n);
  bfs;
end.

转载于:https://www.cnblogs.com/olahiuj/p/5781240.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值