Ural1053 (GCD)

来源:互联网 发布:mac上的图片浏览 编辑:程序博客网 时间:2024/06/03 17:07

1053. Pinocchio

Time limit: 1.0 second
Memory limit: 64 MB
Father Carlo got the commission to make Pinocchio. Client expressed a wish to be unknown and he left material and insisted on finding Pinocchio's nose length as a result of performing the following algorithm:
  1. There's a set of N numbered blanks with integer lengths.
  2. If the set consists of only one blank, then it's length can be admitted as the length of Pinocchio's nose
  3. Let's choose some 2 blanks
    1. If lengths of the blanks coincide, then one of the blanks is eliminated from the set and algorithm goes back to point 2 to be repeated.
    2. If lengths of the blanks are different, then the piece of the long blank is sawed off and its length must be equal to the length of the other blank. Then the algorithm is repeated from point 2.
Example. There are 3 blanks in a set with lengths: 2, 3, 4. Then the change of the blank lengths can be shown in the following table. As a result Pinocchio will get the nose with length of 1.Length of the
first blankLength of the
second blankLength of the
third blankComments234Initial blank lengths214Sawing off the second blank213Sawing off the third blank212Sawing off the third blank112Sawing off the first blank-12The first blank is eliminated-11Sawing off the third blank--1The second blank is eliminated

Input

The first line contains integer N (1 ≤ N ≤ 1000). The other N successive lines contain integersL1,L2, …, LN.
1 ≤ L1, L2, …, LN ≤ MaxLongInt.

Output

Output should contain either one number (Pinocchio nose length), or the word IMPOSSIBLE (in upper case) if the nose length cannot be defined.

Sample

inputoutput
3234
1
题目描述就不多说了,还以为时直接简单模拟的水题,但是TLE,后来突然想到了GCD,就是简单的GCD,求所有数的最大公约数嘛。。。真是too young ,too naive!贡献了一次TLE。。
#include<iostream>#include<cstdio>#include<cstring>using namespace std;#define N 1005int a[N];int gcd(int a,int b){if(a<b)swap(a,b);if(b==0)return a;else return gcd(b,a%b);} int main(){int n;int i,j;scanf("%d",&n);for(i=0;i<n;i++) scanf("%d",&a[i]); int tmp=a[0];for(i=1;i<n;i++){   tmp=gcd(tmp,a[i]);} cout<<tmp<<endl;}


0 0
原创粉丝点击