Hdu 1086 You can Solve a Geometry Problem too[判断线段相交,完整版]

来源:互联网 发布:淘宝零食推荐知乎健康 编辑:程序博客网 时间:2024/05/02 09:58

题目链接:点击打开链接

 题目的意思很简单,就是很多线段的交点有多少。算的留下一个模板吧。

code:

#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>using namespace std;const int N = 1e2 + 5;struct Point{    double x, y;};struct Vector{    double x, y;};struct Line{    Point a, b;}A[N];double operator *(Vector a, Vector b){    return a.x * b.y - b.x * a.y;}Vector operator - (Point a, Point b){//计算向量ab    Vector tmp;    tmp.x = b.x - a.x;    tmp.y = b.y - a.y;    return tmp;}bool OnLine(Line ab, Point c){//判断c是否在线段ab上    int maxx = max(ab.a.x, ab.b.x);    int minx = min(ab.a.x, ab.b.y);    int maxy = max(ab.a.y, ab.b.y);    int miny = min(ab.a.y, ab.b.y);    if(c.x >= minx && c.x <= maxx && c.y >= miny && c.y <= maxy) return true;    return false;}bool Judge(Line X, Line Y){    Vector a, b, c, a1, b1, c1;    a = X.a - X.b; b = Y.a - X.b; c = Y.b - X.b;    a1 = Y.a - Y.b; b1 = X.a - Y.b; c1 = X.b - Y.b;    double dir1 = a * b, dir2 = a * c, dir3 = a1 * b1, dir4 = a1 * c1;    if(dir1 * dir2 < 0 && dir3 * dir4 < 0) return true;    else if(dir1 == 0 && OnLine(X, Y.a)) return true;    else if(dir2 == 0 && OnLine(X, Y.b)) return true;    else if(dir3 == 0 && OnLine(Y, X.a)) return true;    else if(dir4 == 0 && OnLine(Y, X.b)) return true;    else return false;}int main(){    int n;    while(scanf("%d", &n) && n){        for(int i = 1; i <= n; i ++){            scanf("%lf %lf %lf %lf",&A[i].a.x, &A[i].a.y, &A[i].b.x, &A[i].b.y);        }        int ans = 0;        for(int i = 1; i < n; i ++){            for(int j = i + 1; j <= n; j ++){                if(Judge(A[i], A[j]))                ans ++;            }        }        printf("%d\n", ans);    }    return 0;}

小小 判断线段相交的模板。

0 0
原创粉丝点击