传送门:点击打开链接
题意:参照那个表格,,最后给出的n*n个那表格中的数字,是打乱的,求还原出是哪n个数字
思路:可以发现,G表格中,正斜对角线恰好是ai,因为对自己的gcd就等于自己。那么也就是说所有的ai最后都会存在于n*n个数字中,进一步一想我们就能发现,最大的那个数字一定是A数组中的,因为gcd不可能比原数大。那么第二次我再选出最大的,此时这个最大的会与之前已确定的A数组中的会有gcd,这个gcd在n*n中应该是出现了两次,gcd(A[i],A[j])和gcd(A[i],A[j]),所以我们需要把这个去掉。然后再找出最大的,再枚举可能的gcd,再去掉一些,再继续模拟,,直到n个数字全部出来为止。
那么问题是,要怎么维护才能达到高效性呢。
先用map维护某一个数字出现了多少次。因为map的键位也是从小到大排序的,所以我们只需要取出--H.end(),这会是map的最后一个迭代器。他的first一定是最大的,那么他就是A中的第一个数字了。每次确定某个数字是A中之后,就将H中对应的数字个数-1,如果发现个数为0了,就直接删除迭代器。对于新加入A的数字,我们去枚举它与之前已经确定的A的数字可能产生的gcd,在H中将这些数字都减去,同样的个数为0删除迭代器。这样一循环题目就做完了。总的来说还是一道很有意思的贪心题目,也很有意思的考到了map
#include<map>
#include<set>
#include<cmath>
#include<ctime>
#include<stack>
#include<queue>
#include<cstdio>
#include<cctype>
#include<string>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define fuck printf("fuck")
#define FIN freopen("input.txt","r",stdin)
#define FOUT freopen("output.txt","w+",stdout)
using namespace std;
typedef long long LL;
const int MX = 250000 + 5;
LL A[MX], B[MX];
int vis[MX], rear;
LL gcd(LL a, LL b) {
return b ? gcd(b, a % b) : a;
}
int main() {
int n; //FIN;
while(~scanf("%d", &n)) {
rear = 0;
map<LL, int>H;
map<LL, int>::iterator it;
for(int i = 1; i <= n * n; i++) {
scanf("%I64d", &A[i]);
H[A[i]]++;
}
it = --H.end();
LL Max = it->first;
it->second--;
if(!it->second) H.erase(it);
B[++rear] = Max;
while(rear < n) {
it = --H.end();
Max = it->first;
for(int i = 1; i <= rear; i++) {
LL g = gcd(B[i], Max);
if((H[g] -= 2) == 0) {
H.erase(H.find(g));
}
}
it->second--;
if(!it->second) H.erase(it);
B[++rear] = Max;
}
for(int i = 1; i <= rear; i++) {
printf("%I64d%c", B[i], i == rear ? '\n' : ' ');
}
}
return 0;
}