题目大意:求直线相交交点、或者判断共线,比线段相交简单些,(前者可利用方程,后者要先判断是否相交,然后用面积法求得交点)
思路:克莱姆法则
题目大意:给出四个点确定两条直线。如果是一条线输出“LINE”,如果平行输出“NONE”, 如果有交点输出交点坐标。
思路:注意是直线,不是线段啊。
用两点式推出两条直线方程 :
(y1 - y2)x + (x2 - x1)y = x2y1 - x1y2;
(y3 - y4)x + (x4 - x3)y = x4y3 - x3y4;
又由Cramer法则:
a1x + b1y = c1;
a2x + b2y = c2;
(D是系数的行列式)(Dj是在D中的行列式,用方程右边的常数去替换D中j列的数)
D = a1b2 - a2b1; D1 = c1b2 - c2b1; D2 = a1c2 - a2c1;
D != 0时, x = D1 / D, y = D2 / D; 得到交点坐标。
D = 0时;如果a1 / a2 = b1 / b2 = c1 / c2 , 则四个点在一条直线上;否则两直线平行,无交点。
AC code:
#include <stdio.h> #include <stdlib.h>
int main () { int n; int x1, y1, x2, y2, x3, y3, x4, y4; int a1, b1, c1, a2, b2, c2; int D, D1, D2; double x, y; scanf ("%d", &n); printf ("INTERSECTING LINES OUTPUT\n"); while (n--) { scanf ("%d%d%d%d%d%d%d%d",&x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4); a1 = y1 - y2; // 由公式推出的关系 a2 = y3 - y4; b1 = x2 - x1; b2 = x4 - x3; c1 = x2 * y1 - x1 * y2; c2 = x4 * y3 - x3 * y4; D = a1 * b2 - a2 * b1; if (D) { // D != 0 运用Cramer法则求交点 D1 = c1 * b2 - c2 * b1; D2 = a1 * c2 - a2 * c1; x = (double)((double)D1 / D); y = (double)((double)D2 / D); printf ("POINT %.2lf %.2lf\n", x, y); } else if (a1 * c2 == a2 * c1 && b1 * c2 == b2 * c1) // 两直线重合 printf ("LINE\n"); else printf ("NONE\n"); } printf ("END OF OUTPUT\n"); //system ("pause"); return 0; }