CF#479 D:Divide by three, multiply by two(DFS)

题目链接

Divide by three, multiply by two


题意

有一个数x,经过一下两种操作

  • ×2
  • ÷3

结果记录在黑板上,但顺序是乱的,现在要我们求正确的顺序

解题思路

直接搜索,搜到结果回溯时记录就可以了

Code

#include "cstdio"
#include "iostream"
#include "cstring"
#include "map"
#include "vector"
#include "cstdlib"

using namespace std;
typedef long long LL;
const int maxn=105;
LL a[maxn];
map<LL,int> cnt;
vector<LL> v;
int n;
bool DFS(LL x,int c)
{
    bool res=false;
    if(c==n)
    {
        v.push_back(x);
        return true;
    }
    if(x%3==0&&cnt[x/3])
    {
        if(DFS(x/3,c+1))
            v.push_back(x),res=true;
    }
    if(cnt[x*2])
    {
        if(DFS(x*2,c+1))
            v.push_back(x),res=true;
    }
    return res;
}

int main()
{
    //freopen("input.txt","r",stdin);

    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
        cnt[a[i]]++;
    }
    for(int i=0;i<n;i++)
    {
        if(DFS(a[i],1))
        {
            for(int i=n-1;i>=0;i--)
            {
                cout<<v[i];
                if(i==0)
                    cout<<endl;
                else
                    cout<<' ';
            }
            return 0;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值