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.
题意:给出n个在坐标轴上的点,并给出每个点的坐标xi,你的初始位置是X,你有两种遍历方式。
1.向前走D步。
2.向后走D步。
你需要遍历到每个点至少一次。
现在需要求出最大的D满足条件。
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
3 3 1 7 11
Sample Output 1
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.
Sample Input 2
3 81 33 105 57
Sample Output 2
24
Sample Input 3
1 1 1000000000
Sample Output 3
999999999
我们不难发现,想要从X走到每个点,我们离每个点的距离必定是D的整数倍。
所以显而易见,我们直接求出初始点到每个点的距离,D的最大值就是n个距离的最大公约数。
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<iostream>
using namespace std;
int maxn=-1,n,m,a[100005],minn=1926081700;
int main()
{
std::ios::sync_with_stdio(false);
cin>>n>>m;
for(register int i=1;i<=n;++i)
{
cin>>a[i];
a[i]=abs(a[i]-m);
minn=min(minn,a[i]);
}
int k=sqrt(minn);
bool flag;
for(register int i=minn;i>=k;--i)
{
flag=0;
if(!(minn%i))
{
for(register int j=1;j<=n;++j)
if(a[j]%i)
{
flag=1;
break;
}
if(!flag)
{
cout<<i;
return 0;
}
flag=0;
int q=minn/i;
for(register int j=1;j<=n;++j)
if(a[j]%q)
{
flag=1;
break;
}
if(!flag)
maxn=max(maxn,i);
}
}
if(maxn!=-1)
cout<<maxn;
else
cout<<1;
return 0;
}