AcWing 1246. 等差数列
考察:gcd
和蒜头君的数轴基本一样的题,但是要注意等差数列包括d=0,要注意除0的问题
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 using namespace std; 5 typedef long long ll; 6 const int N = 100000; 7 ll a[N],b[N]; 8 ll ans; 9 int gcd(int a,int b) 10 { 11 return b?gcd(b,a%b):a; 12 } 13 int main() 14 { 15 int n; 16 scanf("%d",&n); 17 for(int i=1;i<=n;i++) scanf("%d",&a[i]); 18 sort(a+1,a+n+1); 19 for(int i=1;i<n;i++) b[i] = a[i+1]-a[i]; 20 ans = b[1]; 21 for(int i=2;i<n;i++) ans = gcd(ans,b[i]); 22 int res = ans==0?n:(a[n]-a[1])/ans+1; 23 printf("%d\n",res); 24 return 0; 25 }