Codeforces Round #323 (Div. 2) C. GCD Table 暴力

C. GCD Table

Time Limit: 1 Sec  

Memory Limit: 256 MB

题目连接

http://codeforces.com/contest/583/problem/C

Description

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.

Input

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.

Output

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.

Sample Input

4
2 1 2 3 4 3 2 6 1 1 2 2 1 2 3 2

Sample Output

4 3 6 2

HINT

题意

由n个数,可以构成n*n的gcd矩阵(如图

给你n*n个数,表示这个n*n矩阵的元素(是任意顺序的

然后让你找到这n个数,满足这个gcd矩阵

题解:

首先,我们可以分析出几个结论

1.最大的数,一定是答案

2.出现次数为奇数的,一定是答案         //然而这个条件并没有什么用……

做法,我们就选择最大的数,然后让这个数和前面取到的数,都会产生两个gcd,于是就在数列中把这两个gcd删去就好了

注意,每两个数之间,一定会产生两个gcd的

代码:

#include<iostream>
#include<stdio.h>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;

#define maxn 620

int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}
int a[maxn*maxn];
map<int,int> H;
vector<int> ans;
int main()
{
    int n;scanf("%d",&n);
    for(int i=1;i<=n*n;i++)
    {
        scanf("%d",&a[i]);
        H[a[i]]++;
    }
    sort(a+1,a+n*n+1);
    for(int i=n*n;i;i--)
    {
        if(!H[a[i]])
            continue;
        H[a[i]]--;
        for(int j=0;j<ans.size();j++)
            H[gcd(ans[j],a[i])]-=2;
        ans.push_back(a[i]);
    }
    for(int i=0;i<=n-1;i++)
        cout<<ans[i]<<" ";
    cout<<endl;
}
原文地址:https://www.cnblogs.com/qscqesze/p/4854114.html