题目:小Q今天在上厕所时想到了这个问题:有n个数,两两组成二元组,差最小的有多少对呢?差最大呢?
输入描述:
输入包含多组测试数据。
对于每组测试数据:
N - 本组测试数据有n个数
a1,a2…an - 需要计算的数据
保证:
1<=N<=100000,0<=ai<=INT_MAX.
输出描述:
对于每组数据,输出两个数,第一个数表示差最小的对数,第二个数表示差最大的对数。
输入例子:
6
45 12 45 32 5 6
输出例子:
1 2
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
#include <set>
using namespace std;
void work(vector<int> &myArray, int n) {
map<int, int> cnt;
set<int> mySet;
sort(myArray.begin(), myArray.end());
int element;
for(int i = 0; i < n; i++) {
element = myArray[i];
if(!cnt.count(element)) {
cnt[element] = 1;
} else {
cnt[element]++;
}
mySet.insert(element);
}
int maxValue;
if(myArray[0] != myArray[n-1]){
maxValue = cnt[myArray[0]] * cnt[myArray[n-1]];
} else {
maxValue = 0;
}
bool isExitZero = false;
vector<int> value;
int v;
for(int i = 1; i < n; i++) {
v = myArray[i] - myArray[i-1];
value.push_back(v);
if(v == 0) {
isExitZero = true;
break;
}
}
sort(value.begin(), value.end());
int minValue = 0;
if(isExitZero) {
int u;
for(set<int>::iterator it = mySet.begin(); it != mySet.end(); it++) {
u = *it;
if(cnt[u] >= 2) {
minValue += (cnt[u] * (cnt[u] - 1))/2;
}
}
} else {
int x = value[0];
for(int i = 0; i < n-1; i++) {
if(value[i] == x){
minValue++;
}
else {
break;
}
}
}
printf("%d %d\n", minValue, maxValue);
}
int main()
{
int n, read;
vector<int> myArray;
while(scanf("%d", &n) != EOF) {
myArray.clear();
for(int i = 0; i < n; i++) {
scanf("%d", &read);
myArray.push_back(read);
}
if(n == 1) {
printf("0 0\n");
} else {
work(myArray, n);
}
}
return 0;
}
/**
4
2 2 2 2
5
4 5 6 7 8
6
1 2 2 2 3 3
8
2 2 1 1 3 3 4 4
6
45 12 45 32 5 6
**/