[ABC262C] Min Max Pair
Problem Statement
You are given a sequence $a = (a_1, \dots, a_N)$ of length $N$ consisting of integers between $1$ and $N$.
Find the number of pairs of integers $i, j$ that satisfy all of the following conditions:
- $1 \leq i \lt j \leq N$
- $\min(a_i, a_j) = i$
- $\max(a_i, a_j) = j$
Constraints
- $2 \leq N \leq 5 \times 10^5$
- $1 \leq a_i \leq N \, (1 \leq i \leq N)$
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
$N$ $a_1$ $\ldots$ $a_N$
Output
Print the answer.
Sample Input 1
4 1 3 2 4
Sample Output 1
2
$(i, j) = (1, 4), (2, 3)$ satisfy the conditions.
Sample Input 2
10 5 8 2 2 1 6 7 2 9 10
其实对于合法的数对可以分成两种:$$a_i=i,a_j=j,i<j$$ $$a_i=j,a_j=i,i>j$$
对于第一种,统计有多少个 \(a_i=i\) ,设有 \(cnt\) 个,则答案为 \(\frac{cnt*(cnt-1)}{2}\)
对于第二种,如果\(a_{a_i}=i\),答案增加1.
#include<cstdio>
const int N=5e5+5;
int n,a[N],cnt;
long long ans;
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",a+i);
if(a[i]==i)
{
ans+=cnt;
cnt++;
}
else if(a[a[i]]==i)
++ans;
}
printf("%lld",ans);
}