您的位置:首页 > 其它

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

2014-07-17 18:12 369 查看
题目链接:点击打开链接

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

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
;

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;
}


小小 判断线段相交的模板。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐