One day Polycarp decided to rewatch his absolute favourite episode of well-known TV series "Tufurama". He was pretty surprised when he got results only for season 7 episode 3 with his search query of "Watch Tufurama season 3 episode 7 online full hd free". This got Polycarp confused — what if he decides to rewatch the entire series someday and won't be able to find the right episodes to watch? Polycarp now wants to count the number of times he will be forced to search for an episode using some different method.
TV series have n seasons (numbered 1 through n), the i-th season has ai episodes (numbered 1 through ai). Polycarp thinks that if for some pair of integers x and y (x < y) exist both season x episode y and season y episode x then one of these search queries will include the wrong results. Help Polycarp to calculate the number of such pairs!
The first line contains one integer n (1 ≤ n ≤ 2·105) — the number of seasons.
The second line contains n integers separated by space a1, a2, ..., an (1 ≤ ai ≤ 109) — number of episodes in each season.
Print one integer — the number of pairs x and y (x < y) such that there exist both season x episode y and season y episode x.
5 1 2 3 4 5
0
3 8 12 7
3
3 3 2 1
2
题意:每一季都有很多集,每个数字代表这一季有多少集,问像第一季的第二集和第二季的第一集这样的组合有多少对.
思路:就相当于问,设第i组为ai,问1~ai组有多少个组的数大于等于i.当然最多就n个组,ai再大也没用.
我们可以先从数字小的开始,用树状数组维护,每次取来一个更大的数就从上一次维护好的节点继续往下维护,查询前ai个组中有多少大于等于i的就是查询当前树状数组中大于等于i的值有多少.
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5+5;
struct node
{
int num;
int sum;
} p[maxn],q[maxn];
int n;
long long sum[maxn];
bool cmp(node a,node b)
{
return a.sum< b.sum;
}
int lowbit(int x)
{
return x&(-x);
}
void add(int x,int val)
{
for(int i = x;i<= n;i+= lowbit(i))
sum[i]++;
}
long long get_sum(int x)
{
long long ans = 0;
for(int i = x;i>= 1;i-= lowbit(i))
ans+= sum[i];
return ans;
}
int main()
{
cin>>n;
for(int i = 1;i<= n;i++)
{
scanf("%d",&p[i].sum);
p[i].num = i;
q[i] = p[i];
}
sort(p+1,p+n+1,cmp);
long long ans = 0;
int j = 1;
for(int i = 1;i<= n;i++)
{
int k = min(n,p[i].sum);
for(;j<= k;j++)
add(min(q[j].sum,n),1);
ans+= get_sum(n)-get_sum(p[i].num-1); //查询大于等于p[i].num的有多少
if(p[i].num<= p[i].sum)//记得把自己去掉
ans--;
}
cout<<ans/2<<endl;
return 0;
}