C - Skip
Time limit : 2sec / Memory limit : 1024MB
Score : 300 points
Problem Statement
There are N cities on a number line. The i-th city is located at coordinate xi.
Your objective is to visit all these cities at least once.
In order to do so, you will first set a positive integer D.
Then, you will depart from coordinate X and perform Move 1 and Move 2 below, as many times as you like:
- Move 1: travel from coordinate y to coordinate y+D.
- Move 2: travel from coordinate y to coordinate y−D.
Find the maximum value of D that enables you to visit all the cities.
Here, to visit a city is to travel to the coordinate where that city is located.
Constraints
- All values in input are integers.
- 1≤N≤105
- 1≤X≤109
- 1≤xi≤109
- xi are all different.
- x1,x2,…,xN≠X
Input
Input is given from Standard Input in the following format:
N X x1 x2 … xN
Output
Print the maximum value of D that enables you to visit all the cities.
Sample Input 1
Copy
3 3 1 7 11
Sample Output 1
Copy
2
Setting D=2 enables you to visit all the cities as follows, and this is the maximum value of such D.
- Perform Move 2 to travel to coordinate 1.
- Perform Move 1 to travel to coordinate 3.
- Perform Move 1 to travel to coordinate 5.
- Perform Move 1 to travel to coordinate 7.
- Perform Move 1 to travel to coordinate 9.
- Perform Move 1 to travel to coordinate 11.
题意:从X出发,要求最大的D,保证每个点都能走到,可以看出其实就是求每个点距离X的距离的最大公约数;
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include<map>
typedef long long ll;
using namespace std;
void read(int &x){int f=1;x=0;char s=getchar();while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}x*=f;}
int GCD(int a,int b){
return b==0?a:GCD(b,a%b);
}
int main(){
int n,m;
int a[100005];
int b[100005];
read(n);
read(m);
int h=0;
int top=0;
for(int i=0;i<n;i++){
read(a[i]);
b[top++]=abs(a[i]-m);
}
h=GCD(b[0],b[1]);
for(int i=2;i<n;i++){
h=GCD(b[i],h);
}
printf("%d\n",h);
}