题意:给n个数,问这些数里相反数有几对。0与自己成相反数。
Input
5
-3 3 0 0 3
Output
3
Input
3
0 0 0
Output
3
Note
In the first sample the couples of opposite clients are: (1,2), (1,5) и (3,4).
In the second sample any couple of clients is opposite.
此题开始想用暴力枚举去做,然后果断超时了。
后来观察样例发现:当数值不为0时,ans=正数个数*负数个数,当数值为0时,ans=k*(k-1)/2。k为0的个数。由于数组的下标无法储存负数,所以需要用到STL的map。
#include <stdio.h>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
typedef long long ll;
int n;
ll t;
map<int, ll>mp;
ll ans = 0;
int main()
{
cin >> n;
ll cnt = 0;
for (int i = 1; i <= n; i++)
{
cin >> t;
cnt = max(t, cnt);
mp[t]++;
}
for (int i = 0; i <= cnt; i++) {
if (i == 0)
ans += (mp[i] * (mp[i] - 1)) / 2;
else
ans += mp[i] * (mp[-i]);
}
cout << ans << endl;
return 0;
}