Life is a Line
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)
Total Submission(s): 1927 Accepted Submission(s): 471
Problem Description
There is a saying: Life is like a line, some people are your parallel lines, while others are destined to meet you.
Maybe have met, maybe just a matter of time, two unparallel lines will always meet in some places, and now a lot of life (i.e. line) are in the same coordinate system, in a given open interval, how many pairs can meet each other?
Maybe have met, maybe just a matter of time, two unparallel lines will always meet in some places, and now a lot of life (i.e. line) are in the same coordinate system, in a given open interval, how many pairs can meet each other?
Input
There are several test cases in the input.
Each test case begin with one integer N (1 ≤ N ≤ 50000), indicating the number of different lines.
Then two floating numbers L, R follow (-10000.00 ≤ L < R ≤ 10000.00), indicating the interval (L, R).
Then N lines follow, each line contains four floating numbers x1, y1, x2, y2 (-10000.00 ≤ x1, y1, x2, y2 ≤ 10000.00), indicating two different points on the line. You can assume no two lines are the same one.
The input terminates by end of file marker.
Output
For each test case, output one integer, indicating pairs of intersected lines in the open interval, i.e. their intersection point’s x-axis is in (l, r).
Sample Input
3
0.0 1.0
0.0 0.0 1.0 1.0
0.0 2.0
0.0 2.0
1.0 2.0
0.0 2.5 2.5 0.0
0.0 2.5 2.5 0.0
Sample Output
1
Author
iSea @ WHU
Source
题意:
给出n条线段两个端点的坐标以及x轴的一个范围l,r,问在这个范围内直线有几个交点。
代码:
/*
两直线在l,r之内有交点当且仅当(a1-a1)*(b1-b2)<0,a1,b1是其中一条直线与l,r的两个交点,这样按照a排一次序
只要b有交错就会有交点,然后就转化成求逆序数,先按照a从小到大排,给他们编一个号,在按照b从小到大排序
这样只要求编号的逆序数即可。特殊情况是直线平行y轴,此时他与其他的不平行于y轴的直线都相交。
求逆序数是当前的数的位置减去前面比他小的数的个数也就是正序数个数。
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int A[];
struct Lu
{
double a,b;
int num;
}L[];
bool cmp1(Lu x,Lu y)
{
if(x.a==y.a)
return x.b<y.b;
return x.a<y.a;
}
bool cmp2(Lu x,Lu y)
{
if(x.b==y.b)
return x.a<y.a;
return x.b<y.b;
}
int lowbit(int id)
{
return id&(-id);
}
void add(int id,int v)
{
while(id<=){
A[id]+=v;
id+=lowbit(id);
}
}
int qury(int id)
{
int s=;
while(id>){
s+=A[id];
id-=lowbit(id);
}
return s;
}
int main()
{
int n;
double l,r,x1,x2,y1,y2;
while(scanf("%d",&n)!=EOF){
scanf("%lf%lf",&l,&r);
int ans=,tem=,cnt=;
for(int i=;i<n;i++){
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
if(x1==x2){ //在l,r以外就去掉,在l,r以内要计算,就是这里wa到吐血。
if(x1>l&&x1<r) tem++;
continue;
}
L[cnt].a=y2+(y1-y2)*(l-x2)/(x1-x2);
L[cnt++].b=y2+(y1-y2)*(r-x2)/(x1-x2);
}
sort(L,L+cnt,cmp1);
for(int i=;i<cnt;i++){
L[i].num=i+;
}
sort(L,L+cnt,cmp2);
memset(A,,sizeof(A));
for(int i=;i<cnt;i++){
add(L[i].num,);
ans+=(i-qury(L[i].num-)); //求逆序数
}
printf("%d\n",ans+tem*cnt);
}
return ;
}