Codeforces Round #479 (Div. 3) D. Divide by three, multiply by two 【dfs】

题意

一个数要么除以3,要么除以2,共记录n个数,但是n个数顺序打乱了,要你求新序列保证相互之间是两倍或者三分之一关系

思路

直接搜索完事,找到一条路就return 0,因为先考虑的是3再考虑2,最后打印的时候要反序输出。

code

#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
typedef long long ll;
const int maxn=110;
int n;
ll a[maxn];
map<ll,bool> vis;
vector<ll> v;
bool dfs(ll x,int t){
    bool flag=false;
    if(t==n){
        v.push_back(x);
        return true;
    }
    if(x%3==0&&vis[x/3]){
        if(dfs(x/3,t+1))
            v.push_back(x),flag=true;
    }
    if(vis[x*2]){
        if(dfs(x*2,t+1))
            v.push_back(x),flag=true;
    }
    return flag;
}
int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
        vis[a[i]]=true;
    }
    for(int i=0;i<n;i++){
        if(dfs(a[i],1)){
            for(int i=n-1;i>0;i--)
                cout<<v[i]<<" ";
            cout<<v[0]<<endl;
            return 0;
        }
    }
    return 0;
}

学如逆水行舟,不进则退
发布了407 篇原创文章 · 获赞 954 · 访问量 12万+

猜你喜欢

转载自blog.csdn.net/weixin_42429718/article/details/104097995