试题名称: 相邻数对
时间限制: 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>
using namespace std;
int main()
{
int n,m=0,sum=0;
int a[10001]={0};
cin>>n;
while(n--)
{
int t;
cin>>t;
a[t]=1;
}
for(int i=1;i<1001;i++)
{
if (a[i]==1&&a[i-1]==1)
m++;
else
{
sum=sum+m;
m=0;
}
}
cout<<sum<<endl;
return 0;
}
粘贴一个网上搜到的代码,思路更简洁一点
[cpp] view plaincopy
#include<iostream>
using namespace std;
int a[10000]={0};
int main(){
int n,sum=0,x;
cin>>n;
while(n--){
cin>>x;
a[x]=1;
if(x+1<10000 && a[x+1]){
sum++;
}
if(x-1>=0 && a[x-1]){
sum++;
}
}
cout<<sum<<endl;
return 0;
}