The GCD table G of size n × n for an array of positive integers a of length n is defined by formula
Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both xand y, it is denoted as . For example, for array a = {4, 3, 6, 2} of length 4 the GCD table will look as follows:
Given all the numbers of the GCD table G, restore array a.
The first line contains number n (1 ≤ n ≤ 500) — the length of array a. The second line contains n2 space-separated numbers — the elements of the GCD table of G for array a.
All the numbers in the table are positive integers, not exceeding 109. Note that the elements are given in an arbitrary order. It is guaranteed that the set of the input data corresponds to some array a.
In the single line print n positive integers — the elements of array a. If there are multiple possible solutions, you are allowed to print any of them.
4 2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2
4 3 6 2
1 42
42
2 1 1 1 1
1 1
题意是给出一个打乱了顺序的GCD表,里面是一个数组元素两两的GCD。求这个数组。
首先这个表中的最大元素肯定是数组元素,然后与其他在数组中的元素求GCD,将结果从表中删除,然后再找最大元素,肯定是数组元素。如此往复暴力。
代码:
#pragma warning(disable:4996)
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#include <queue>
#include <map>
using namespace std;
typedef long long ll;
int n;
int val[250005];
vector<int>res;
map<int, int>ha;
int exc(int a, int b)
{
if (a == 0)
{
return b;
}
return exc(b%a, a);
}
int main()
{
//freopen("i.txt", "r", stdin);
//freopen("o.txt", "w", stdout);
int i, j, k;
scanf("%d", &n);
for (i = 1; i <= n*n; i++)
{
scanf("%d", &val[i]);
ha[val[i]]++;
}
sort(val + 1, val + n*n + 1);
for (i = n*n; i >= 1; i--)
{
if (ha[val[i]] == 0)continue;
ha[val[i]]--;
for (j = 0; j < res.size(); j++)
{
int t = exc(val[i], res[j]);
ha[t] = ha[t] - 2;
}
res.push_back(val[i]);
}
for (i = 0; i < res.size(); i++)
{
printf("%d ", res[i]);
}
//system("pause");
return 0;
}