2021CPC_C_Average of Two Numbers

题目:https://cpc.csgrandeur.cn/csgoj/problemset/problem?pid=1159

Description
Given a list of n different numbers, which number in this list can be represented as an average of any two other numbers in the same list?

Input
There are multiple test cases.

The first line of each test case is an integer n, where 3 ≤ n ≤ 1000. The second line contains n different positive integers seperated by spaces, denoting the list of numbers. The numbers are in ascending order and every number in this list is less than 109.

Output
For each test case, output the number of numbers in this list which can be represented as an average of any two other numbers in the same list.

Sample Input
3
1 2 3
6
3 4 6 7 8 9
Sample Output
1
3
Hint
In the first case, 2 can be represented by (1 + 3) / 2.

In the second case, 6 can be represented by (3 + 9) / 2, 7 can be represented by (6 + 8) / 2, 8 can be represented by (7 + 9) / 2.

思路:
先观察那个数之间的关系,通过a[i]减左边的数和右边的数-a[i]作比较相等答案就加1,因为左边的数到a[i]和右边的数到a[i]的距离相等那就说明这两个数和除2一定等于a[i],所以还有其它这样的一对数值也是一样的避免重复就直接break

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <map>
#include <set>
#include <cstdlib>
using namespace std;


int main(){
	
	int n;
	
	while(scanf("%d",&n) != EOF){
		int a[1010];
		for(int i = 1;i<=n;i++) scanf("%d",&a[i]);
		
		int l,r,ans = 0;
		for(int i = 2;i<n;i++){
			
			l = i-1,r = i+1;
			while(l>0&&r<=n){
				if((a[i]-a[l]) == (a[r]-a[i])){
					ans++;
					break;
				}else if(a[i]-a[l] < a[r]-a[i]) l--;
				else r++;
			}
		}
		printf("%d\n",ans);
	}
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值