题意:给你一个长度为\(n\)的序列\(a\).对它重新排列,使得\(a_{i+1}=a_{i}/3\)或\(a_{i+1}=2*a_{i}\).输出重新排列后的序列.
题解:经典DFS,遍历这个序列,对每个数dfs,每次dfs使\(len+1\),当\(len=n\)时,说明这个序列已经满足条件了,输出并且标记一下,防止还有另外的情况导致多输出.
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#define ll long long
#define fi first
#define se second
#define pb push_back
#define me memset
const int N = 1e6 + 10;
const int mod = 1e9 + 7;
using namespace std;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
int n;
bool st[N];
int len;
ll ans[N];
ll a[N];
bool ok;
void dfs(int x,int len){
if(len==n && !ok){
ok=1;
for(int i=1;i<=n;++i) printf("%lld ",ans[i]);
return;
}
st[x]=true;
for(int i=1;i<=n;++i){
if(!st[i] && (a[i]*3==ans[len] || ans[len]*2==a[i])){
ans[len+1]=a[i];
dfs(i,len+1);
}
}
st[x]=false;
}
int main() {
ios::sync_with_stdio(false);cin.tie(0);
cin>>n;
for(int i=1;i<=n;++i) cin>>a[i];
for(int i=1;i<=n;++i){
ans[1]=a[i];
memset(st,0,sizeof(st));
dfs(i,1);
}
return 0;
}
Codeforces Round #479 (Div. 3) D. Divide by three, multiply by two (DFS)
原文:https://www.cnblogs.com/lr599909928/p/12924952.html