原题链接:xinz
描述
Winter vacation is coming soon ! Everyone wants to go home soon ! But the way to home is so far that the time in the train will become very boring. Yu loves the train very much , and every time he went home , he will by a ticket near the window .
There are many rivers through the way to Yu’s home . Yu is very boring so he begin to calculate the number of rivers pass through the way .
Finally ,he got a number. Could guess the number?
To make it easier , we now imagine the way is a segment A between Point a(x1,y1) and b(x2,y2) , and the river is a line L which pass Point c(X,Y) and d(X0,Y0).If A and L has a common point , we think the river pass through the way. You should calculate how many rivers pass through the way.
输入
Multiple cases, for each case:
First line contains 5 numbers N , x1,y1,x2,y2 means there are N rivers , and the way is start at x1,y1, end at x2,y2 .
Then following n line each contains four numbers X,Y,X0,Y0,means the nth line pass the point (X,Y),(X0,Y0).
输出
Each case output one number, indicating how many rivers pass through the way.
样例输入
1 1 1 3 3
1 3 3 1
样例输出
1
题解
意思是河流是条直线,路径是条线段,问有多少条直线与线段相交。
根据两点式可以写出直线方程
- 直线L: ( x - x1 )( y2 - y1 ) - ( y - y1 )( x2 - x1 ) = 0
因此我们可以发现
- 点在直线上 ( x - x1 )( y2 - y1 ) - ( y - y1 )( x2 - x1 ) = 0
- 点在直线上方 ( x - x1 )( y2 - y1 ) - ( y - y1 )( x2 - x1 ) > 0
- 点在直线下方 ( x - x1 )( y2 - y1 ) - ( y - y1 )( x2 - x1 ) < 0
所以我们只要满足两个点不在同一个方向就可以确定直线与线段相交
AC代码
#include<iostream>
#include<cmath>
using namespace std;
int main(){
int sx,sy,gx,gy,n;
while(~scanf("%d%d%d%d%d",&n,&sx,&sy,&gx,&gy)){
int ans=0;
while(n--){
int x1,y1,x2,y2;
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
int a=(sx-x1)*(y2-y1)-(sy-y1)*(x2-x1);
int b=(gx-x1)*(y2-y1)-(gy-y1)*(x2-x1);
if(!a||!b)ans++;
else if(a<0&&b>0)ans++;
else if(a>0&&b<0)ans++;
}
printf("%d\n",ans);
}
return 0;
}