CCF CSP 編程題目和解答-----試題名稱:相鄰數對-------201409-1

問題描述
試題編號: 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<vector>
#include<algorithm>
#include<string>
#include<map>
#include<strstream>
using namespace std;
int main()
{
	int n;
	cin >> n ;
	map<int, int> all;
	for (int i = 0; i < n; i++)
	{
		int tem;
		cin >> tem;
		all.insert(pair<int,int>(tem,0));
	}
	int count = 0;
	map<int, int>::iterator it = all.begin();
	for (it; it != all.end(); it++)
	{
		int tem = it->first;
		int less = tem - 1;
		int more = tem + 1;
		if (all.find(less) != all.end())
			count++;
		if (all.find(more) != all.end())
			count++;
	}
	count /= 2;//所有的對子都重複算了兩遍
	cout << count;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章