Codeforces #323 C. GCD Table (脑洞题、Induction)

题意:

GCD tablen2,

分析:

a1a2...an.gcd(ai,aj)min(ai,a=amin(i,j).
gcd(an,an)=anaigcd(ai,aj),(i,j)1i,jn.an,an.
gcd(ai,aj),(i,j)1i,jn,1min(i,j)n1.
,gcd(ai,aj)amin(i,j)an1=gcd(an1,an1).gcd(an1,an1),an1.
an1an,gcd(an1,an1),gcd(an1,an),gcd(an,an1).
gcd(ai,aj),(i,j)1i,jn,1min(i,j)n2.
k{n21},ak,gcd(ak,ak),gcd(ai,ak),gcd(ak,ai),i(k,n].
multisetmap,O(n2logn)

代码:
map:

//
// Created by TaoSama on 2015-10-04
// Copyright (c) 2015 TaoSama. All rights reserved.
//
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>

using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 3e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;

int n, ans[505];

int main() {
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
// freopen("out.txt","w",stdout);
#endif
    ios_base::sync_with_stdio(0);

    while(scanf("%d", &n) == 1) {
        map<int, int> mp;
        for(int i = 0; i < n * n; ++i) {
            int x; scanf("%d", &x);
            ++mp[x];
        }

        for(int i = 1; i <= n; ++i) {
            ans[i] = mp.rbegin()->first;
            for(int j = 1; j <= i; ++j) {
                int x = __gcd(ans[i], ans[j]);
                mp[x] -= 2;
                if(mp[x] <= 0) mp.erase(x);
            }
        }
        for(int i = 1; i <= n; ++i)
            printf("%d%c", ans[i], " \n"[i == n]);
    }
    return 0;
}

multiset:

//
// Created by TaoSama on 2015-10-04
// Copyright (c) 2015 TaoSama. All rights reserved.
//
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>

using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 3e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;

int n, ans[505];

int main() {
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
// freopen("out.txt","w",stdout);
#endif
    ios_base::sync_with_stdio(0);

    while(scanf("%d", &n) == 1) {
        multiset<int> s;
        for(int i = 0; i < n * n; ++i) {
            int x; scanf("%d", &x);
            s.insert(x);
        }

        for(int i = 1; i <= n; ++i) {
            ans[i] = *s.rbegin();
            s.erase(--s.end());
            for(int j = 1; j < i; ++j) {
                int x = __gcd(ans[i], ans[j]);
                s.erase(s.find(x));
                s.erase(s.find(x));
            }
        }
        for(int i = 1; i <= n; ++i)
            printf("%d%c", ans[i], " \n"[i == n]);
    }
    return 0;
}

你可能感兴趣的:(gcd,codeforces)