【CCF】201403-1 相反数
问题描述
有 N 个非零且各不相同的整数。请你编一个程序求出它们中有多少对相反数(a 和 -a 为一对相反数)。
输入格式
第一行包含一个正整数 N。(1 ≤ N ≤ 500)。
第二行为 N 个用单个空格隔开的非零整数,每个数的绝对值不超过1000,保证这些整数各不相同。
第二行为 N 个用单个空格隔开的非零整数,每个数的绝对值不超过1000,保证这些整数各不相同。
输出格式
只输出一个整数,即这 N 个数中包含多少对相反数。
样例输入
5
1 2 3 -1 -2
1 2 3 -1 -2
样例输出
2
'''暴力破除''' n=int(input()) a=list(map(int,input().split())) res=0 for i in range(n): for j in range(i+1,n): if a[i]+a[j]==0: res=res+1 print(res)
'''整数暴力搜索:利用python的list特性''' n=int(input()) a=list(map(int,input().split())) res=0 for i in a: if -i in a: res=res+1 print(int(res/2))
//C++用映射map做标记,和利用python的list特性 有异曲同工之妙
#include <iostream> #include <map> using namespace std; int main() { map<int, int> m; int n, a, cnt = 0; cin >> n; for(int i=0; i<n; i++) { cin >> a; if (m.find(-a) == m.end()) m[a]++; // 判断负值是否已经存在,构建Map 此时不存在 else cnt++; //存在 计数++ } cout << cnt << endl; // 输出结果 return 0; }
'''字符串 暴力搜索''' n=int(input()) a=input().split() res=0 for i in a: if '-'+i in a: res=res+1 print(res)
'''标记数组''' N=10001 n=int(input()) a=list(map(int,input().split())) num=[0]*N res=0 for i in a: if(num[abs(i)]==1):#已经有数字 res=res+1 num[abs(i)]=1 print(res)
'''排序''' N=10001 n=int(input()) a=list(map(int,input().split())) a.sort()#排序 #两个指针 从两边往中间找 left=0 right=n-1 res=0 while(left<right and a[left]<0 and a[right]>0): if a[left]==-a[right]: res=res+1 left=left+1 right=right-1 elif -a[left]>a[right]: left=left+1 elif -a[left]<a[right]: right=right-1 print(res)

浙公网安备 33010602011771号