B - Opposites Attract

B - Opposites Attract

Everybody knows that opposites attract. That is the key principle of the “Perfect Matching” dating agency. The “Perfect Matching” matchmakers have classified each registered customer by his interests and assigned to the i-th client number ti ( - 10 ≤ ti ≤ 10). Of course, one number can be assigned to any number of customers.
“Perfect Matching” wants to advertise its services and publish the number of opposite couples, that is, the couples who have opposite values of t. Each couple consists of exactly two clients. The customer can be included in a couple an arbitrary number of times. Help the agency and write the program that will find the sought number by the given sequence t1, t2, …, tn. For example, if t = (1,  - 1, 1,  - 1), then any two elements ti and tj form a couple if i and j have different parity. Consequently, in this case the sought number equals 4.
Of course, a client can’t form a couple with him/herself
Input
The first line of the input data contains an integer n (1 ≤ n ≤ 105) which represents the number of registered clients of the “Couple Matching”. The second line contains a sequence of integers t1, t2, …, tn ( - 10 ≤ ti ≤ 10), ti — is the parameter of the i-th customer that has been assigned to the customer by the result of the analysis of his interests.
Output
Print the number of couples of customs with opposite t. The opposite number for x is number  - x (0 is opposite to itself). Couples that only differ in the clients’ order are considered the same.
Note that the answer to the problem can be large enough, so you must use the 64-bit integer type for calculations. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.
Examples
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的个数。
方法:首先我想到的是两层循环,但由于数字太大,时间超限了。后来又想到了下标法,但下标不能是负数。最后用的map,代码如下:

#include"cstdio"
#include"csring"
#include"algorithm"
#incldue"map"
using namespace std;
int main()
{
     int n,t;
     map<int,long long> m;
     while(cin>>n)
     {
           for(int i=0;i<n;i++)
           {
                 cin>>t;
                 m[t]++;
           }
           long long sum=0;
           for(int i=-10;i<0;i++)
           {
                 if(m[i]!=0)
                 {
                     sum=sum+m[i]*m[-i];
                 }
           }
           long long h=m[0];
           sum+=(h*(h-1))/2;
           cout<<sum<<endl;
     }
     return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值