Problem Statement
Given an array of
N
integers
A
(
A
1
,
A
2
,
.
.
.
,
A
N
)
, find the number of pairs
(
i
,
j
)
of integers satisfying all of the following conditions:
1
≤
i
<
j
≤
N
A
i
≠
A
j
Constraints
All values in input are integers.
2
≤
N
≤
3
×
10
5
1
≤
A
i
≤
10
9
Input
Input is given from Standard Input in the following format:
N
A
1
A
2
…
A
N
Output
Print the answer as an integer.
Sample Input 1
3
1 7 1
Sample Output 1
2
In this input, we have
A
(
1
,
7
,
1
)
.
For the pair
(
1
,
2
)
,
A
1
≠
A
2
.
For the pair
(
1
,
3
)
,
A
1
A
3
.
For the pair
(
2
,
3
)
,
A
2
≠
A
3
.
Sample Input 2
10
1 10 100 1000 10000 100000 1000000 10000000 100000000 1000000000
Sample Output 2
45
Sample Input 3
20
7 8 1 1 4 9 9 6 8 2 4 1 1 9 5 5 5 3 6 4
Sample Output 3
173
思路
找到每种数有几个,然后用总数减这种数的个数,该个数就是满足条件的个数,但是如果每个数都这样求就肯定会有重复,而且是把所有存在的都多算了一边,所以答案除以2就好了。
代码
#include<bits/stdc++.h>
using namespace std;map<long long int,long long int> res;long long int n,num[300005]={0},cnt=0;
int main()
{
cin>>n;
long long int sum=0;
for(long long int i=1;i<=n;i++)
{
cin>>num[i];
if(res[num[i]]==0)
{
cnt++;
}
res[num[i]]++;
}
for(long long int i=1;i<=n;i++)
{
sum+=(n-res[num[i]]);//这样算会有重复的,正好是两倍
}
cout<<sum/2;
return 0;
}
坑点
要开long long