Description
There are n cities situated along the main road of Berland. Cities are represented by their coordinates — integer numbers a1, a2, ..., an. All coordinates are pairwise distinct.
It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money — he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.
It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs.
Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.
Input
The first line contains one integer number n (2 ≤ n ≤ 2·105).
The second line contains n integer numbers a1, a2, ..., an ( - 109 ≤ ai ≤ 109). All numbers ai are pairwise distinct.
Output
Print two integer numbers — the minimal distance and the quantity of pairs with this distance.
Sample Input
4 6 -3 0 4
2 1
3 -2 0 2
2 2
解题思路:
题目是让找出任意两点间的最小差值,并统计其个数,对输入坐标升序排序的话,最小值一定在前一项与后一项的差中
细节处理:
别忘了给min赋一个较大的初始值 因为- 10^9 ≤ ai ≤ 10^9,所以min要赋初值2*10^9以上
代码:
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n,i,c;
while(cin>>n)
{
vector<int> a;
for(i=0;i<n;i++)
{cin>>c; a.push_back(c);}
sort(a.begin(),a.end());
int cha,min=2000000009; int num=0;
for(i=1;i<n;i++)
{
cha=a[i]-a[i-1];
if(cha<min){ min=cha; num=1;}
else {if(cha==min) num++;}
}
cout<<min<<" "<<num<<endl;
a.clear();
}
return 0;
}