其他分享
首页 > 其他分享> > POJ 3304 Segments

POJ 3304 Segments

作者:互联网

几何 直线与线段相交

如果每条线段的投影在直线上有重合的点,那么我们通过这一点做一条直线必定会经过所有的线段!!
那么我们考虑把这条直线随意移动到与其中一条线段的某个端点重合,此时直线还是过了所有线段,我们再以该点为中心顺时针或逆时针旋转直线,让这条直线恰好经过另一个线段的某个端点,此时直线一定还是经过所有线段,且经过了其中某两个线段的两个端点。
根据这个思路我们可以枚举所有端点,用叉积判断直线与线段是否相交,复杂度O(n^3)

#include <iostream>
#include <cstdio>
#include <cmath>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
    int X = 0, w = 0; char ch = 0;
    while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
    while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
    return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
    A ans = 1;
    for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
    return ans;
}

const int N = 105;
const double eps = 1e-8;
struct Point { double x,  y;} s[N], e[N];
int n, _;

double mul(const Point &a, const Point &b, const Point &c){
    return (a.x - c.x) * (b.y - c.y) - (a.y - c.y) * (b.x - c.x);
}

bool check(const Point &a, const Point &b){
    if(fabs(a.x - b.x) < eps && fabs(a.y - b.y) < eps) return false;
    for(int i = 0; i < n; i ++){
        if(mul(a, b, s[i]) * mul(a, b, e[i]) > eps)
            return false;
    }
    return true;
}

int main(){

    while(scanf("%d", &_) != EOF){
        for(; _; _ --){
            scanf("%d", &n);
            for(int i = 0; i < n; i ++){
                scanf("%lf%lf%lf%lf", &s[i].x, &s[i].y, &e[i].x, &e[i].y);
            }
            if(n == 1){
                printf("Yes!\n");
                continue;
            }
            bool flag = false;
            for(int i = 0; i < n; i ++){
                for(int j = i + 1; j < n; j ++){
                    if(check(s[i], s[j]) || check(s[i], e[j]) || check(e[i], e[j]) || check(e[i], s[j])){
                        flag = true;
                        break;
                    }
                }
                if(flag) break;
            }
            if(flag) printf("Yes!\n");
            else printf("No!\n");
        }
    }
    return 0;
}

标签:直线,return,Point,int,线段,POJ,const,3304,Segments
来源: https://www.cnblogs.com/onionQAQ/p/10742341.html