**Pair of Topics **
题目描述
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by ai units for the teacher and by bi units for the students.
The pair of topics i and j (i<j) is called good if ai+aj>bi+bj (i.e. it is more interesting for the teacher).
Your task is to find the number of good pairs of topics.
Input
The first line of the input contains one integer n (2≤n≤2⋅105) — the number of topics.
The second line of the input contains n integers a1,a2,…,an (1≤ai≤10^9), where ai is the interestingness of the i-th topic for the teacher.
The third line of the input contains n integers b1,b2,…,bn (1≤bi≤109), where bi is the interestingness of the i-th topic for the students.
Output
Print one integer — the number of good pairs of topic.
Examples
Input #1
5
4 8 2 6 2
4 5 4 1 3
Output #1
7
Input #2
4
1 3 2 4
1 3 2 4
Output #2
0
Solution
运用了树状数组求逆序对的思想。令ci = ai - bi,原式移项得到
ai - bi > bj - aj (i < j)
即 ci > - cj (i < j)
我们发现与逆序对很相似,只是多了一个负号,为了处理负数和大数,我们需要进行离散化,要比较ci和-cj的大小,所以把ai - bi和bi - ai 一起离散化,然后每次查询已插入的小于等于bi - ai的(a - b)数量,当前是已经插入i - 1 个,故i - 1 - 查询的值即为比bi - ai大的(a - b)数量,计入答案中,然后插入ai - bi。
正向扫一遍最后得到答案。
代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
const int SZ = 500000 + 20;
const int INF = 0x3f3f3f3f;
ll ans;
ll tree[SZ],n,a[SZ],b[SZ],all[SZ];
inline int lowbit(int x)
{
return x & (-x);
}
inline void update(int x)
{
while(x <= 2 * n)
{
tree[x] += 1;
x += lowbit(x);
}
}
inline ll query(int x)
{
ll sum = 0;
while(x)
{
sum += tree[x];
x -= lowbit(x);
}
return sum;
}
int main()
{
memset(tree,0,sizeof(tree));
scanf("%d",&n);
for(int i = 1;i <= n;i ++ ) scanf("%lld",&a[i]);
for(int j = 1;j <= n;j ++ ) scanf("%lld",&b[j]);
for(int i = 1;i <= n;i ++ )
{
ll temp = a[i];
a[i] = a[i] - b[i];
b[i] = b[i] - temp;
all[i] = a[i];
all[i + n] = b[i];
}
sort(all + 1,all + 2 * n + 1);
int sum = unique(all + 1,all + 2 * n + 1) - all - 1;
ans = 0;
for(int i = 1;i <= n;i ++ )
{
a[i] = lower_bound(all + 1,all + 1 + sum,a[i]) - all;
b[i] = lower_bound(all + 1,all + sum + 1,b[i]) - all;
}
for(int i = 1;i <= n;i ++ )
{
ans += (i - 1 - query(b[i]));
update(a[i]);
}
printf("%lld",ans);
return 0;
}
2020.3.17