Gold Rush 深搜 DFS

题目描述

Initially you have a single pile with n gold nuggets. In an operation you can do the following:

  • Take any pile and split it into two piles, so that one of the resulting piles has exactly twice as many gold nuggets as the other. (All piles should have an integer number of nuggets.)

    One possible move is to take a pile of size 66 and split it into piles of sizes 22 and 44 , which is valid since 44 is twice as large as 22 .

Can you make a pile with exactly m gold nuggets using zero or more operations?

输入格式

The first line contains an integer t ( 1≤t≤1000 ) — the number of test cases.

The only line of each test case contains two integers n and m ( 1≤n,m≤107 ) — the starting and target pile sizes, respectively.

输出格式

For each test case, output "YES" if you can make a pile of size exactly m , and "NO" otherwise.

You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

题意翻译

题意简述

本题有 t 组数据。对于每组数据,你都会得到 n 个金币。

现在,你可以对这 n 个金币进行分堆。每次分堆只能分成两堆,并且需要使分堆后的一堆恰好是另一堆的两倍。同时,分成的两堆都必须有整数个金币。

请你判断:在经过多次或不经过分堆后能否有任意一堆的金币数为 �m。如果可以,请输出 YES 或其它任意的大小写形式;否则,请输出 NO 或其它任意的大小写形式。

样例解释

对于样例一中的第一组数据,我们可以采用如图的形式分堆: 

对于第二组数据,它可以采用如下的分堆方式:

{9}→{6,3}→{4,2,3}{9}→{6,3}→{4,2,3}

在每次分堆前,被分开的堆被标为红色。

对于第三组数据,我们无法进行分堆操作。

对于第四组数据,我们不能把少的金币变成更多的一堆。

Translate by @tianbiandeshenghuo11

输入输出样例

输入 #1复制

11
6 4
9 4
4 2
18 27
27 4
27 2
27 10
1 1
3 1
5 1
746001 2984004

输出 #1复制

YES
YES
NO
NO
YES
YES
NO
YES
YES
NO
NO

说明/提示

The first test case is pictured in the statement. We can make a pile of size 44 .

In the second test case, we can perform the following operations: {9}→{6,3}→{4,2,3}{9}→{6,3}→{4,2,3} . The pile that is split apart is colored red before each operation.

In the third test case, we can't perform a single operation.

In the fourth test case, we can't end up with a larger pile than we started with.

思路讲解:

我认为这道题就是唬人的,看着题干可能是英文的,这么长的篇幅,感觉吓人,其实很简单,将一个数每次分为2部分,分成一个数和一个数的两倍,既然它可以分为三分之一和三分之二,那么这个数一定可以将3 整除,这也是我们这道题判断终止条件的关键


代码实现: 

#include<bits/stdc++.h>
using namespace std;
int n,m;
bool f=false; 
void dfs(int x)
{
    if(x==m) f=true; 
    if(x%3!=0) return;  // 终止条件
    dfs(x/3); 
    dfs((x/3)*2);
}
int main()
{
    int T; cin>>T;
    while(T--)
    {
        f=false;
        cin>>n>>m;
        dfs(n);
        if(f==true) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值