原题链接:http://codeforces.com/contest/977/problem/D
除三乘二
现在有两种运算符f(x)、g(x):
f(x) = x / 3 if x % 3 == 0 else nan
g(x) = x * 2
(nan 意为 not a number,即值不存在。也就是说当x不是3的倍数的时候,不能使用f(x))
现在给定n个整数,让你重新排列这些整数[a1, a2 … an],并在相邻的两数中间插入f(x)或g(x),使得:
a2 = u1(a1)
a3 = u2(a2)
…
an = un - 1(an - 1)
ui(x)为f(x)或g(x)。
输入格式:
第一行为整数n (2 <= n <= 100)
第二行为n个整数,1 <= ai <= 3 * 1e18
输入数据保证答案一定存在
样例输入:
INPUT
6
4 8 6 3 12 9OUTPUT
9 3 6 12 4 8
解释:
f(9) = 3
g(3) = 6
g(6) = 12
f(12) = 4
g(4) = 8
思路:
因为n比较小,可以暴力枚举每个点是否存在一条符合条件的路径。也就是遍历每个点看看其之后的点是否符合 f(x) f ( x ) or g(x) g ( x ) ,如果符合条件那么就在这两个点之间连一条边。因为保证有解,所以必定可以找到一个点的入度为0,从这个点开始遍历,然后记录dfs的路径。最后输出。
#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
using namespace std;
const int N = 1e5+5;
int vis[N],in[N];
long long a[N];
vector<int> edge[N];
int n;
vector<long long> res;
void dfs (long long root) {
vis[root] = 1;
res.push_back(a[root]);
for (int i = 0; i < edge[root].size(); ++i) {
int tmp = edge[root][i];
if (!vis[tmp])
dfs(tmp);
}
}
void solve()
{
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i != j) {
if (a[i]%3==0 && a[i]/3 == a[j]) {
edge[i].push_back(j);
in[j]++;
}
else if (a[i] * 2 == a[j]) {
edge[i].push_back(j);
in[j]++;
}
}
}
}
for (int i = 0; i < n; ++i) {
if (in[i] == 0)
dfs(i);
}
}
int main()
{
cin>>n;
for (int i = 0; i < n; ++i) {
cin>>a[i];
}
solve();
for (int i = 0; i < n; ++i)
cout<<res[i]<<" ";
cout << endl;
return 0;
}