HDU5902 GCD is FunnyGCD

Posted 海岛Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU5902 GCD is FunnyGCD相关的知识,希望对你有一定的参考价值。

GCD is Funny
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2577 Accepted Submission(s): 626

Problem Description
Alex has invented a new game for fun. There are n integers at a board and he performs the following moves repeatedly:

  1. He chooses three numbers a, b and c written at the board and erases them.
  2. He chooses two numbers from the triple a, b and c and calculates their greatest common divisor, getting the number d (d maybe gcd(a,b), gcd(a,c) or gcd(b,c)).
  3. He writes the number d to the board two times.

It can be seen that after performing the move n−2 times, there will be only two numbers with the same value left on the board. Alex wants to know which numbers can left on the board possibly. Can you help him?

Input
There are multiple test cases. The first line of input contains an integer T (1≤T≤100), indicating the number of test cases. For each test case:

The first line contains an integer n (3≤n≤500) – the number of integers written on the board. The next line contains n integers: a1,a2,…,an (1≤ai≤1000) – the numbers on the board.

Output
For each test case, output the numbers which can left on the board in increasing order.

Sample Input
3
4
1 2 3 4
4
2 2 2 2
5
5 6 2 3 4

Sample Output
1 2
2
1 2 3

Source
BestCoder Round #87

问题链接HDU5902 GCD is Funny
问题简述:(略)
问题分析:GCD有关的问题,不解释。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* HDU5902 GCD is Funny */

#include <bits/stdc++.h>

using namespace std;

const int N = 500;
const int A = 1000;
int a[N], ans[A + 1];

int main()
{
    int t, n;
    scanf("%d", &t);
    while (t--) {
        scanf("%d", &n);
        for (int i = 0; i < n; i++) scanf("%d", &a[i]);

        memset(ans, 0, sizeof ans);
        for (int i = 0; i < n; i++)
            for (int j = 0; j < i; j++)
                ans[__gcd(a[i], a[j])] = 1;

        int flag = 1, cnt = n;
        while (flag && cnt > 3) {
            cnt--;
            flag = 0;
            for (int i = 1; i <= A; i++)
                if (ans[i])
                    for (int j = 0; j < n; j++) {
                        int p = __gcd(i, a[j]);
                        if (ans[p] == 0) {
                            flag = 1;
                            ans[p] = 1;
                        }
                    }
        }

        int p = 1;
        for (int i = 1; i <= A; i++)
            if (ans[i]) {
                if (p) {
                    printf("%d", i);
                    p--;
                } else
                    printf(" %d", i);
            }
        printf("\\n");
    }

    return 0;
}

以上是关于HDU5902 GCD is FunnyGCD的主要内容,如果未能解决你的问题,请参考以下文章

hdu 5902 GCD is Funny

GCD is Funny(hdu 5902)

[HDU5902]GCD is Funny(xjb搞)

hdu-2685 I won't tell you this is about number theory---gcd和快速幂的性质

hdu 5381 The sum of gcd 莫队+预处理

HDU 2588 GCD(欧拉函数)