CF792A New Bus Route 题解
Content
给定一个长度为 \(n\) 的数列 \(a_1,a_2,a_3,...,a_n\),求这个序列当中差的绝对值最小的数对并求出这样的数对的个数。
数据范围:\(2\leqslant n\leqslant 2\times 10^5,-10^9\leqslant a_i\leqslant 10^9\)。
Solution
先把这个数对排序,然后一个一个去比较得到差的绝对值的最小值,最后再去一个一个比较看差的绝对值的最小值是否等于这个数对的差的绝对值即可。
Code
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
int n, a[200007], minx = 2147483647, cnt;
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
sort(a + 1, a + n + 1);
for(int i = 1; i < n; ++i) minx = min(minx, abs(a[i] - a[i + 1]));
printf("%d ", minx);
for(int i = 1; i < n; ++i)
if(minx == abs(a[i] - a[i + 1])) cnt++;
printf("%d", cnt);
}

浙公网安备 33010602011771号