AtCoder Grand Contest 018 A - Getting Difference

探讨了一个数学问题,即通过从盒子中取出两个球并替换为它们差的绝对值的新球,判断是否能通过一系列操作得到特定数值的球。分析了问题的解决策略,并提供了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A - Getting Difference

Time limit : 2sec / Memory limit : 256MB

Score : 300 points

Problem Statement

There is a box containing N balls. The i-th ball has the integer Ai written on it. Snuke can perform the following operation any number of times:

Take out two balls from the box. Then, return them to the box along with a new ball, on which the absolute difference of the integers written on the two balls is written.

Determine whether it is possible for Snuke to reach the state where the box contains a ball on which the integer K is written.

Constraints

1≤N≤10^5
1≤Ai≤10^9
1≤K≤10^9
All input values are integers.

Input
Input is given from Standard Input in the following format:

N K
A1 A2 … AN

Output

If it is possible for Snuke to reach the state where the box contains a ball on which the integer K is written, print POSSIBLE; if it is not possible, print IMPOSSIBLE.

Sample Input 1

3 7
9 3 4

Sample Output 1

POSSIBLE

First, take out the two balls 9 and 4, and return them back along with a new ball, abs(9−4)=5. Next, take out 3 and 5, and return them back along with abs(3−5)=2. Finally, take out 9 and 2, and return them back along with abs(9−2)=7. Now we have 7 in the box, and the answer is therefore POSSIBLE.

Sample Input 2

3 5
6 9 3

Sample Output 2

IMPOSSIBLE

No matter what we do, it is not possible to have 5 in the box. The answer is therefore IMPOSSIBLE.

Sample Input 3

4 11
11 3 7 15

Sample Output 3

POSSIBLE

The box already contains 11 before we do anything. The answer is therefore POSSIBLE.

Sample Input 4

5 12
10 2 8 6 4

Sample Output 4

IMPOSSIBLE


当时也不知道干什么去了,就差一步就AC了……真的是太菜了

题目大意

给出一个长度为N的初始数列,数列中每一个数都是正整数。 现在可以执行任意次以下操作:

从当前数列中任选两个数,将它们差的绝对值加入这个数列。

问是否可以通过若干次操作使得数列中含有K。


分析

设初始数列中最大的数为Max
首先分析特判:

如果Max比K要小,那么是不可能的

之后从最简单情况,也就是一开始数列中只有两个数的情况分析:

如果能够得到1,那么剩下的判断就比较简单了。那么很自然地,我们会想知道通过若干次操作后能够得到的最小的数是多少。
模拟一下整个过程,容易发现:

这个过程正是辗转相除算法的过程! 那么能够得到的最小的数就是两数的最大公约数!

设两数的最大公约数为gcd,结合辗转相除算法的原理稍加分析,这个时候能够得到的所有可能的数是不大于Max的数中,gcd的倍数。

接下来进行推广,就很容易发现正解了。

1.若Max小于K,那么输出“IMPOSSIBLE”。
2.当Max不小于K时,若这N个数的gcd能被K整除,那么输出“POSSIBLE”,否则输出“IMPOSSIBLE”。

#include<stdio.h>
#include<algorithm>
using namespace std;
int K,N,Max,GCD;

int gcd(int a,int b)
{
    if(!b)return a;
    return gcd(b,a%b);
}

int main()
{
    int i,x;

    scanf("%d%d%d",&N,&K,&x);
    Max=GCD=x;
    for(i=2;i<=N;i++)
    {
        scanf("%d",&x);
        Max=max(Max,x);
        GCD=gcd(GCD,x);
    }

    if(K%GCD==0&&K<=Max)puts("POSSIBLE");
    else puts("IMPOSSIBLE");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值