CCF-CSP 201409-1 adjacent pairs

Problem description
  Given n different integers, ask how many pairs of integers there are, and their values ​​differ by exactly 1.
Input format
  The first line of input contains an integer n, which represents the number of given integers.
  The second line contains the given n integers.
Output format
  outputs an integer, indicating the number of pairs whose values ​​are exactly 1 different.
Sample input
6
10 2 6 3 7 8
Sample output
3
Sample description
  Pairs whose values ​​differ by exactly 1 include (2, 3), (6, 7), (7, 8).
Evaluation use case scale and convention
  1 <= n <= 1000, the given integer is a non-negative integer not exceeding 10000.

Summary of experience:
use an array to store the input data, and then sort. After traversing the array to determine.

C ++ code:

#include<bits/stdc++.h>
using namespace std;
int main() {
	int n,cnt = 0;
	scanf("%d",&n);
	int num[n];
	for(int i=0;i<n;i++){
		scanf("%d",&num[i]);
	}
	sort(num,num+n);
	for(int i=1;i<n;i++){ //从1开始,避免数组越界
		if(1 == num[i]-num[i-1]) cnt++;
	}
	printf("%d",cnt);
	return 0;
}
Published 111 original articles · won praise 2 · Views 3533

Guess you like

Origin blog.csdn.net/m0_38088647/article/details/100513572