hdu 5902

題意:

對一塊板上的一串數字進行移動,移動規則:

    1. 取其中三個數字(a,b,c)中的兩個的最大公約數,那麼就可以得到三個最大公約數:gcd(a, b), gcd(b,c), gcd(a, c)。然後把這三個數寫到板上。

    2. 重複上述動作n-2次

思路:模擬+暴力枚舉

代碼:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <map>
#include <cstring>
using namespace std;
const int maxn = 934;
int arr[1647] = {}, rec[23456] = {};
bool book[6475] = {};
int gcd(int xx, int yy)
{
    return xx % yy == 0 ? yy : gcd(yy, xx % yy);
}
int main()
{
    int _;
    scanf("%d", &_);
    while(_--)
    {
        memset(book, false, sizeof(book));
        memset(rec, 0, sizeof(rec));
        int cnt = 0, n;
        scanf("%d", &n);
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &arr[i]);
        }
        for(int i = 1; i < n; i++)
        {
            for(int j = i + 1; j <= n; j++)
            {
                int gg = gcd(arr[i], arr[j]);
                if(!book[gg])
                {
                    rec[++cnt] = gg;
                }
                book[gg] = true;
            }
        }
        int len = 1;
        bool flag = true;
        while(len < n - 2 && flag)
        {
            flag = false;
            len++;
            int cc = cnt;
            for(int i = 1; i <= cnt; i++)
            {
                for(int j = 1; j <= n; j++)
                {
                    int gg = gcd(rec[i], arr[j]);
                    if(!book[gg])
                    {
                        rec[++cc] = gg;
                        flag = true;
                    }
                    book[gg] = true;
                }
            }
            cnt = cc;
        }
        sort(rec + 1, rec + cnt + 1);
        for(int i = 1; i <= cnt; i++)
        {
            printf("%d", rec[i]);
            if(i < cnt) printf(" ");
        }
        printf("\n");
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章