ACM - Divide by three, multiply by two

Divide by three, multiply by two

泰泰学长喜欢玩数字(不知道什么奇怪的癖好)。他在黑板上写下一个数字 x ,然后进行 n-1 次以下两种操作:
(1) x 除以3 (必须能整除才能进行,即 x mod 3=0)
(2) x 乘以2
每次操作完成后,泰泰学长在黑板上写上这个操作后的新数字,并让这个新数字作为新的 x 继续下一次操作。最后黑板上有 n 个数字。由于泰泰学长是随机在黑板上的位置写数字的,所以他最后忘记了顺序。现在泰泰学长只知道所有的数字,你能帮助泰泰学长找出一种可能的序列吗?(保证答案一定存在)

Input
第一行是数字总数 n (2 ≤ n ≤ 100)。第二行包含 n 个数字a1,a2,…,an (1 ≤ ai ≤3×10^18),注意是不按顺序的。

Output
输出 n 个数字,按照泰泰学长写数字的顺序排列。
保证答案一定存在。

Examples
Input
6
4 8 6 3 12 9
Output
9 3 6 12 4 8
Input
4
42 28 84 126
Output
126 42 84 28
Input
2
1000000000000000000 3000000000000000000
Output
3000000000000000000 1000000000000000000

图结构对此关联数据进行存储,然后使用DFS对图进行遍历。
遍历到终点时,即是一种符合题意的数字排列。

#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#define INF  0x3f3f3f3f
#define mod 998244353
#define PI acos(-1)
using namespace std;
typedef long long ll;

int vis[105];
ll arr[105];
vector<ll> ans;  // 答案数组
vector<int> g[105];  // 图 
int n;
int flag = 0;
void pnt()
{
	for (int i = 0; i < ans.size(); i++) {
		if (i != ans.size() - 1) printf("%lld ", ans[i]);
		else printf("%lld\n", ans[i]);
	}
}

void dfs(int x, int k)
{
	if (flag) return;

	if (!vis[x]) {
		vis[x] = 1;
		ans.push_back(arr[x]);

		if (g[x].size()) { // 该条件为避免for循环在条件判断时的int类型升级
			for (unsigned int j = 0; j <= g[x].size() - 1; j++)
				dfs(g[x][j], k + 1);
		}
		else {
			if (k == n)  // (g[x]为空 && k==n)说明遍历出一种结果
			{
				pnt();
				flag = 1;
				return;
			}
		}

		vis[x] = 0;
		ans.pop_back();
	}
}

int main()
{
	// 存图
	cin >> n;
	for (int i = 1; i <= n; i++)
		cin >> arr[i];

	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++)
			if (arr[j] == arr[i] * 2 || arr[i] == arr[j] * 3)
				g[i].push_back(j);
	// 第i个结点开始
	for (int i = 1; i <= n; i++)
		dfs(i, 1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值