题意:
The pair of topics 𝑖 and 𝑗 (𝑖<𝑗) is called good if 𝑎𝑖+𝑎𝑗>𝑏𝑖+𝑏𝑗 (i.e. it is more interesting for the teacher).
找满足这个不等式的对数
思路:
(单独写的a[i]都是代表题意中的a[i]-b[i])
移项得 𝑎𝑖-𝑏𝑖>𝑏𝑗-𝑎𝑗
我们把
a
i
−
b
i
a_i-b_i
ai−bi放到数组中排序,每次只用找到,i后面有几个大于
−
a
[
i
]
的
即
可
-a[i]的即可
−a[i]的即可,用upper_bound()二分
开始有疑问的就是本来不是有(i<j)这个约束条件吗?排序之后不是乱了吗?实际上我们每次只要找到后面比-a[i]大的即可,然后对于谁是i,谁是j,根据题意换就行了
例如:
5
4 8 2 6 2
4 5 4 1 3
ai-bi
0 3 -2 5 -1
排序后
-2 -1 0 3 5
找第一个-2,比-(-2)大的有3,5
-2原来的位置是3,3的位置是2,5的位置是4
对于-2,3 ai=3 i=2,j=3
对于-2,5 ai=-2 i=3,j=4
还可以换种思路
移项得 𝑎𝑖-𝑏𝑖+𝑏𝑗-𝑎𝑗>0
a[i]数组代表原来的a[i]-b[i]
在数组
a
i
−
b
i
a_i-b_i
ai−bi种找两个数的和大于0即可,正数肯定就是,负数找第一个大于-a[i]的即可,实际和第一种思路一样(第一种就是正负数一起处理了)
代码:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <vector>
#include <math.h>
#include <map>
#include <queue>
#include <set>
#include <stack>
#define pb push_back
#define lb lower_bound
#define ub upper_bound
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define per(i,a,b) for(int i=a;i>=b;i--)
typedef long long ll;
using namespace std;
const int MAXN=2e5+50;
const int inf=0x3f3f3f3f;
const int M=5000*4;
int a[MAXN],b[MAXN];
int c[MAXN],d[MAXN];
int main()
{
std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
int n;
cin>>n;
for(int i=1;i<=n;i++){
cin>>c[i];
}
for(int i=1;i<=n;i++){
cin>>d[i];
}
for(int i=1;i<=n;i++){
a[i]=c[i]-d[i];
}
sort(a+1,a+n+1);
ll ans=0;
for(int i=1;i<=n;i++){
int pos=upper_bound(a+i+1,a+n+1,-a[i])-a-1;
if(pos>=n+1)continue;
ans+=(n-pos);
}
cout<<ans<<endl;
return 0;
}
/*
5
4 8 2 6 2
4 5 4 1 3
*/