- 题目链接:http://codeforces.com/contest/977/problem/D
- 题意:给你一串数字,要你重新排序,使得后一个数是前一个数的两倍或1/3。
- 算法:排序 / dfs
- 思路一:排序。将每个数视为2和3以及?(“?”表示其他因子)的乘积。那么从左到右,因子3的个数一定是非严格递减的,而因子2的个数一定是非严格递增的。所以按其因子中“2”、“3”的个数排序,“2”的个数越多,则越靠右,“3”的个数越多则越靠左。
- 思路二:dfs
#include <bits/stdc++.h>
#define pi acos(-1)
#define fastcin ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const LL LL_INF = 1LL << 62;
const int maxn =100 + 10;
const LL mod = 1e9+7;
LL a[maxn];
pair<LL, LL> pll[maxn];
int main()
{
int n; scanf("%d", &n);
for(int i=0; i<n; i++) scanf("%I64d", &a[i]);
for(int i=0; i<n; i++) {
LL cnt=0, tmp=a[i];
while(tmp%2==0){
tmp/=2;
cnt++;
}
while(tmp%3==0){
tmp/=3;
cnt--;
}
pll[i] = make_pair(cnt, a[i]);
}
sort(pll, pll+n);
for(int i=0; i<n; i++){
printf("%I64d%c", pll[i].second, " \n"[i==n-1]);
}
}
#include <bits/stdc++.h>
#define pi acos(-1)
#define fastcin ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const LL ll_INF = 1LL << 62;
const int maxn =100 + 10;
const LL mod = 1e9+7;
LL a[maxn];
vector<LL> vec;
vector<LL> sot;
bool dfs(LL x)
{
if(sot.size()==0){
return true;
}
int ind = lower_bound(sot.begin(), sot.end(), x*2) - sot.begin();
if(sot[ind] == x*2) {
sot.erase(sot.begin() + ind);
vec.push_back(x*2);
if(dfs(x*2)) return true;
sot.insert(sot.begin()+ind, x*2);
vec.erase(vec.end()-1);
}
ind = lower_bound(sot.begin(), sot.end(), x/3) - sot.begin();
if(x%3==0 && sot[ind]==x/3) {
sot.erase(sot.begin() + ind);
vec.push_back(x/3);
if(dfs(x/3)) return true;
sot.insert(sot.begin()+ind, x/3);
vec.erase(vec.end()-1);
}
return false;
}
int main()
{
int n; scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%I64d", &a[i]);
sot.push_back(a[i]);
}
sort(a, a+n);
sort(sot.begin(), sot.end());
for(int i=0; i<n; i++){
vec.clear();
sot.erase(sot.begin()+i);
vec.push_back(a[i]);
if(dfs(a[i])) break;
sot.insert(sot.begin()+i, a[i]);
vec.erase(vec.end()-1);
}
for(int i=0; i<vec.size(); i++){
printf("%I64d%c", vec[i], " \n"[i==vec.size() -1]);
}
}