二维平面上N个点之间共有C(n,2)条连线。求这C(n,2)条线中斜率小于0的线的数量。
二维平面上的一个点,根据对应的X Y坐标可以表示为(X,Y)。例如:(2,3) (3,4) (1,5) (4,6),其中(1,5)同(2,3)(3,4)的连线斜率 < 0,因此斜率小于0的连线数量为2。
Input
第1行:1个数N,N为点的数量(0 <= N <= 50000) 第2 - N + 1行:N个点的坐标,坐标为整数。(0 <= X[i], Y[i] <= 10^9)
Output
输出斜率小于0的连线的数量。(2,3) (2,4)以及(2,3) (3,3)这2种情况不统计在内。
Input示例
4 2 3 3 4 1 5 4 6
Output示例
2
代码:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <cmath>
#include <ctime>
using namespace std;
typedef long long ll;
typedef pair<ll, int> P;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-10;
const int maxn = 5e4+7;
const int mod = 1e9+7;
int n;
struct G{
int x,y,id;
G(int x,int y,int id):x(x),y(y),id(id){}
G(){}
}s[maxn];
int d[maxn];
ll b[maxn];
void ins(int v){
while(v<=n){
b[v]+=1;
v = v+(v&-v);
}
}
ll sum(int v){
ll res = 0;
while(v>0){
res+=b[v];
v-=(v&-v);
}
return res;
}
bool cmp1(G a,G b){
return a.y==b.y?a.x<b.x:a.y<b.y;
}
bool cmp2(G a,G b){
return a.x==b.x?a.y<b.y:a.x<b.x;
}
int main()
{
scanf("%d",&n);
memset(b,0,sizeof(b));
for(int i = 1;i <= n;i++){
int x,y;
scanf("%d %d",&x,&y);
s[i] = G(x,y,i);
}
sort(s+1,s+n+1,cmp1);
for(int i = 1;i <= n;i++){
d[s[i].id] = i;
}
sort(s+1,s+n+1,cmp2);
ll ans = 1ll*n*(n-1)/2;
for(int i = 1;i <= n;i++){
ans-=sum(d[s[i].id]);
ins(d[s[i].id]);
}
printf("%lld\n",ans);
return 0;
}
涉及的知识:
1、离散化。
2、bit。
总结:
一开始想的的二分,后来是线段树+离散化,最后才用了bit。相对来说,在处理求前缀问题上用bit更加简单方便。
好久没打bit,差点记错。
(x&-x):取出x的二进制的最后一个1。
x = x-(x&-x):bit的求和。
x = x+(x&-x):上一步相反,bit插入。