CCF CSP 201409-1 相邻数对

CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以链接形式注明本文地址

CCF CSP 201409-1 相邻数对

问题描述

  给定n个不同的整数,问这些数中有多少对整数,它们的值正好相差1。

输入格式

  输入的第一行包含一个整数n,表示给定整数的个数。
  第二行包含所给定的n个整数。

输出格式

  输出一个整数,表示值正好相差1的数对的个数。

样例输入

6
10 2 6 3 7 8

样例输出

3

样例说明

  值正好相差1的数对包括(2, 3), (6, 7), (7, 8)。

评测用例规模与约定

  1<=n<=1000,给定的整数为不超过10000的非负整数。

解析

首先排序,然后计算相邻两个数的差。

代码

C++

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main() {
    int N;
    cin >> N;
    vector<int> a(N);
    for(int n=0; n<N; n++) {
        cin >> a[n];
    }
    sort(a.begin(), a.end());
    int cnt = 0;
    for(int n=0; n<N-1; n++) {
        if(abs(a[n]-a[n+1])==1) {
            cnt++;
        }
    }
    cout << cnt;
}

 

posted on 2017-10-16 16:55  meelo  阅读(443)  评论(0编辑  收藏  举报