Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define int long long
- #define db(x) cout << #x << " = " << x << "\n";
- using namespace std;
- int ans[5000];
- signed main() {
- ios::sync_with_stdio(false);
- cin.tie(0);
- int n;
- cin >> n;
- vector <int> a(n), used(n);
- for (int i = 0; i < n; ++i) {
- cin >> a[i];
- }
- int l = 2499, r = 2501;
- set <int> ls, rs, k(a.begin(), a.end());
- ans[2500] = a[n - 1];
- ls.insert(ans[2500]);
- rs.insert(ans[2500]);
- used[n - 1] = 1;
- while (true) {
- int left = -1;
- for (int i = n - 1; i > -1; --i) {
- if (used[i] == 1) continue;
- int j = 0;
- for (int f : ls)
- if (k.count(gcd(f, a[i])))
- ++j;
- if (j == ls.size()) {
- left = 1;
- ans[l--] = a[i];
- used[i] = 1;
- break;
- }
- for (int f : rs)
- if (k.count(gcd(f, a[i])))
- ++j;
- if (j == rs.size()) {
- left = 0;
- ans[r++] = a[i];
- used[i] = 1;
- break;
- }
- }
- if (left == -1) break;
- vector <int> ti;
- if (left == 0) {
- for (int z : rs)
- ti.push_back(gcd(z, ans[r - 1]));
- for (int z : ti)
- rs.insert(z);
- }
- else {
- for (int z : ls)
- ti.push_back(gcd(z, ans[l + 1]));
- for (int z : ti)
- ls.insert(z);
- }
- }
- if (r - l - 1 != n) {
- cout << -1;
- return 0;
- }
- for (int i = l + 1; i < r; ++i)
- cout << ans[i] << ' ';
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement