AtCoder Grand Contest 018 A

来源:互联网 发布:手机遥控玩具车软件 编辑:程序博客网 时间:2024/06/06 17:27

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");}
原创粉丝点击