CSU-ACM2017暑期训练16-树状数组 D - 斜率小于0的连线数量 51Nod - 1107
2017-08-14 22:23
465 查看
D - 斜率小于0的连线数量
二维平面上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 <= Xi, Yi <= 10^9)
Output
输出斜率小于0的连线的数量。(2,3) (2,4)以及(2,3) (3,3)这2种情况不统计在内。
Sample Input
4 2 3 3 4 1 5 4 6
Sample Output
2
由斜率的定义可将问题转化为求出每一点左上方的点的数量总和。于是想到使用树状数组计算区间的和。
若两点具有相同的横坐标或纵坐标,他们连线的斜率显然是不满足条件的。为了方便计算,首先对输入的点集进行排序,使得排序后的数组顺序读取时按照从右至左,从上至下的次序遍历点集。这样就避免了将具有相同纵坐标的点加入结果。此外,再引入一个数组,记录相同的横坐标上是否已经有点,统计前加以判断,从而避免将具有相同横坐标的点加入结果。这样,只需遍历一遍点集即可得到结果。
注意单个数据的数值可能很大,所以对输入数据进行离散化处理。
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <cstring> #include <queue> using namespace std; const int maxn = 50009; int n; struct node{ int x, y; bool operator < (const node &temp)const{ if(y == temp.y) return x > temp.x; return y > temp.y; } }sample[maxn]; int b[maxn], c[maxn], d[maxn]; bool vis[maxn]; void add(int x, int d){ while(x <= n){ c[x] += d; x += x&-x; } } int sum(int x){ int ret = 0; while(x > 0){ ret += c[x]; x -= x&-x; } return ret; } int main(){ #ifdef TEST freopen("test.txt", "r", stdin); #endif // TEST while(cin >> n){ memset(c, 0, sizeof(c)); memset(vis, false, sizeof(vis)); for(int i = 1; i <= n; i++){ scanf("%d%d", &sample[i].x, &sample[i].y); } sort(sample+1, sample+n+1); //开始离散化 for(int i = 1; i <= n; i++) b[i] = sample[i].x; sort(b+1, b+n+1); unique(b+1, b+n+1); for(int i = 1; i <= n; i++) d[i] = lower_bound(b+1, b+n+1, sample[i].x) - b; //完成离散化 long long res = 0; for(int i = 1; i <= n; i++){ if(!vis[d[i]]){ res += sum(d[i]); add(d[i], 1); vis[d[i]] = true; } else{ res += sum(d[i]-1); add(d[i], 1); } } printf("%lld\n", res); } return 0; }
相关文章推荐
- CSU-ACM2017暑期训练16-树状数组 C - 按钮控制彩灯实验 CSU - 1770
- CSU-ACM2017暑期训练16-树状数组 H - Bubble Sort HDU - 5775
- CSU-ACM2017暑期训练16-树状数组 B - Stars POJ - 2352
- CSU-ACM2017暑期训练16-树状数组 A - Ultra-QuickSort POJ - 2299
- 51Nod-1107-斜率小于0的连线数量
- 51Nod - 1107 斜率小于0的连线数量(逆序对)
- 51nod-1107 斜率小于0的连线数量(逆序数+离散化)
- 51NOD——N 1107 斜率小于0的连线数量
- 51nod 1107 斜率小于0的连线数量 (树状数组+离线化)
- 51nod 1107 斜率小于0的连线数量(逆序数)
- 51nod 1107 斜率小于0的连线数量
- D - 斜率小于0的连线数量 51Nod - 1107
- 51nod 1107 斜率小于0的连线数量 树状数组
- 51Nod 1107 斜率小于0的连线数量
- 51nod 1107 斜率小于0的连线的数量 (逆序数)
- 51NOD 1107 斜率小于0的连线数量 坐标离散化+树状数组
- 斜率小于0的连线数量 51NOD - 1107
- 51nod 1107 斜率小于0的连线数量
- (51Nod - 1107)斜率小于0的连线数量
- 51nod-斜率小于0的连线数量(树状数组+离散化)