试题编号: | 201409-1 |
试题名称: | 相邻数对 |
时间限制: | 1.0s |
内存限制: | 256.0MB |
问题描述: |
问题描述
给定n个不同的整数,问这些数中有多少对整数,它们的值正好相差1。
输入格式
输入的第一行包含一个整数n,表示给定整数的个数。
第二行包含所给定的n个整数。
输出格式
输出一个整数,表示值正好相差1的数对的个数。
样例输入
6
10 2 6 3 7 8
样例输出
3
样例说明
值正好相差1的数对包括(2, 3), (6, 7), (7, 8)。
评测用例规模与约定
1<=n<=1000,给定的整数为不超过10000的非负整数。
|
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<limits.h>
#include<algorithm>
#include<memory.h>
using namespace std;
typedef struct
{
int num;
int times;
}data;
bool compare(data a, data b)
{
if(a.times!=0&&b.times!=0)
return a.num > b.num;
else if (a.times == 0){
a.num = -1;
return a.num > b.num;
}
else{
b.num = -1;
return a.num > b.num;
}
}
int main()
{
int n = 0, i = 0, count = 0,temp = 0,j = 0;
cin >> n;
data* head = (data*)malloc(sizeof(data)*n);
memset(head, 0, n*sizeof(data));
/*for (i = 0; i < n; i++)
{
cin >> head[i].num;
head[i].times++;
}*/
for (i = 0; i < n; i++)
{
cin >> temp;
for (j = 0; j <= i; j++){
if (head[j].num == temp){
head[j].times++;
break;
}
}
if (j > i){
head[i].num = temp;
head[i].times++;
}
}
sort(head, head + n,compare);
for (i = 0; i < n - 1; i++)
{
if (head[i + 1].times == 0)break;
if (abs(head[i].num - head[i + 1].num) == 1)count += head[i].times*head[i + 1].times;
}
cout << count << endl;
return 0;
}