线段相交
题目描述
输入线段AB、CD的两端点,判断两线段是否相交(包含端点)
输入格式
有多组数据,每组数据两行,第一行四个整数,分别表示A、B两点坐标,第二行四个整数,分别表示C、D两点坐标。
输出格式
如果线段AB与线段CD相交,输出yes,否则输出no。
输入样例
0 1 1 1
1 0 2 1
1 0 2 1
0 1 2 0
0 0 0 1
1 0 0 0
输出样例
no
yes
yes
import java.util.Scanner;
public class p30 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int ax = sc.nextInt();
int ay = sc.nextInt();
int bx = sc.nextInt();
int by = sc.nextInt();
int cx = sc.nextInt();
int cy = sc.nextInt();
int dx = sc.nextInt();
int dy = sc.nextInt();
if (isIntersect(ax, ay, bx, by, cx, cy, dx, dy)) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
sc.close();
}
public static boolean isIntersect(int ax, int ay, int bx, int by, int cx, int cy, int dx, int dy) {
/*方法:如果线段CD的两个端点C和D,与另一条线段的一个端点(A或B,只能是其中一个)连成的向量,与向量AB做叉乘,
若结果异号,表示C和D分别在直线AB的两边,若结果同号,则表示CD两点都在AB的一边,则肯定不相交。
线段AB与线段CD相交,于是我们可以得到两个向量AC,AD,C和D分别在AB的两边,向量AC在向量AB的逆势针方向,AB×AC > 0;
向量AD在向量AB的顺势针方向,AB×AD < 0,两叉乘结果异号。*/
int c1 = crossProduct(bx - ax, by - ay, cx - ax, cy - ay);
int c2 =