Codeforces977D ---Divide by three, multiply by two 深搜+map存出现的数

传送门:点我

题意:给定n长度的序列,重排成后一个数是前一个数除以三,或者后一个数是前一个数乘二,要求输出这个序列。

思路:大力深搜,对每个数搜除3的和乘2的是否出现过,然后继续搜下去。如果有一个数搜能搜完整个序列,那就输出这个数开始的一整个序列。

代码:

#include<bits/stdc++.h> 
using namespace std;
typedef unsigned long long LL;
int ans = 0,flag = 0;
int n,k;
map<LL,int>ma;
LL b[101];
void dfs(LL x){
    if(ans == n - 1){
        flag = 1;
        for(int i = 0 ; i <= ans; i++){
            i == ans ?printf("%I64u\n",b[i]):printf("%I64u ",b[i]);
        }
        return;
    }
    if(x%3==0&&ma[x/3] == 1){
        ans++;
        b[ans] = x/3;
        dfs(x/3);
    }
    if(ma[x*2] == 1){
        ans++;
        b[ans] = x*2;
        dfs(x*2); 
    }
}
int main(){
    scanf("%d",&n);
    LL a[101];
    for(int i = 0 ; i < n ; i ++){
        cin>>a[i];
        ma[a[i]] = 1;
    }
    vector<LL>v;
    for(int i = 0 ; i < n ; i++){
        ans = 0;
        b[0] = a[i];
        dfs(a[i]);
        if(flag){
            return 0;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/Esquecer/p/9013222.html