CCF-CSP 201403-1 Inverse number

Problem description
  There are N non-zero and different integers. Please write a program to find out how many pairs of opposites (a and -a are opposites).
Input format The
  first line contains a positive integer N. (1 ≤ N ≤ 500).
  The second line is N non-zero integers separated by a single space, the absolute value of each number does not exceed 1000, to ensure that these integers are different.
Output format outputs
  only one integer, that is, how many pairs of opposite numbers are included in these N numbers.
Sample input
5
1 2 3 -1 -2
Sample output
2

Summary
of experience Since the absolute value of each number does not exceed 1000, then an array of length 1001 can be created to store data.
Since each number is different and non-zero, if the sum of the two numbers is 0, it must be a pair of opposite numbers.
In this way, the absolute value of each number can be used as a subscript, and the value is the original value plus this number. If the result is 0 after the addition, then it is a pair of opposite numbers.

C ++ code:

#include<bits/stdc++.h>
using namespace std;
int num[1001];
int main() {
	int n,cnt = 0;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		int a;
		scanf("%d",&a);
		num[abs(a)] += a;
		if(0 == num[abs(a)]){
			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/100516080