HDU 5902 GCD is Funny(GCD)

20 篇文章 4 订阅

GCD is Funny

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 468    Accepted Submission(s): 125


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   n2  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   (1T100) , indicating the number of test cases. For each test case:

The first line contains an integer   n   (3n500)  -- the number of integers written on the board. The next line contains   n  integers:   a1,a2,...,an   (1ai1000) -- 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
#include<stdio.h>
#include<string.h>
#define maxn 100000
int gcd(int x,int y)
{
    if(x%y==0) return y;
    else  return gcd(y,x%y);
}
int num[maxn],a[maxn];
int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
       scanf("%d",&n);
        memset(num,0,sizeof(num));
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
        }

        for(int i=1;i<n;i++)
            for(int j=i+1;j<=n;j++)
                num[gcd(a[i],a[j])]=1;
        int flag=1,cnt=n-1;
        while(flag&&cnt>=3)
        {
            cnt--;
            flag=0;
            for(int i=1;i<=1000;i++)
                if(num[i])
                    for(int j=1;j<=n;j++)
                    {
                        int t=gcd(i,a[j]);
                        if(num[t]==0)
                        {
                            num[t]=1;
                            flag=1;
                        }
                    }
        }

        int t=0;
        for(int i=1;i<=1000;i++)
            if(num[i])
            {
                if(t)
                    printf(" %d",i);
                else{
                    printf("%d",i);
                    t=1;
                }
            }
        printf("\n");
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值