POJ - 1127 Jack Straws

题目链接

AcCode:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int maxn = 25;
const int maxm = 100000;
const double EPS = 1e-10;

double add(double a, double b)
{
    if(abs(a+b) < EPS*(abs(a)+abs(b)))
        return 0;
    return a+b;
}

typedef struct P{
    double x, y;
    P(){}
    P(double x, double y): x(x), y(y) {}
    P operator + (P p){
        return P(add(x, p.x), add(y, p.y));
    }
    P operator - (P p){
        return P(add(x, -p.x), add(y, -p.y));
    }
    P operator * (double d){
        return P(x*d, y*d);
    }
    double dot(P p){    //点乘积
        return add(x*p.x, y*p.y);
    }
    double det(P p){    //叉乘积
        return add(x*p.y, -y*p.x);
    }
};

//判断点p 是否在线段p1 - p2上
bool on_seg(P p1, P p2, P q)
{
    return (p1-q).det(p2-q) == 0 && (p1-q).dot(p2-q) <= 0;
}
//求出p1p2, q1q2的交点
P intersection(P p1, P p2, P q1, P q2)
{
    return p1+(p2-p1) * ((q2-q1).det(q1-p1) / (q2-q1).det(p2-p1));
}

int n, m;
P p[maxn], q[maxn];
int a[maxm], b[maxm];
bool g[maxn][maxn];

bool input()
{
    scanf("%d", &n);
    if(n == 0) return false;
    for(int i = 0; i < n; i++)
        scanf("%lf %lf %lf %lf", &p[i].x, &p[i].y, &q[i].x, &q[i].y);
    m = 0;
    int aa, bb;
    while(scanf("%d %d", &aa, &bb)){
        if(aa == 0 && bb == 0) break;
        a[m] = aa, b[m] = bb;
        m++;
    }
    return true;
}

void solve()
{
    for(int i = 0; i < n; i++){
        g[i][i] = true;
        for(int j = 0; j < i; j++){
            if((p[i]-q[i]).det(p[j]-q[j]) == 0){
                g[i][j] = g[j][i] = on_seg(p[i], q[i], p[j]) || on_seg(p[i], q[i], q[j]) || on_seg(p[j], q[j], p[i]) || on_seg(p[j], q[j], q[i]);
            }
            else {
                P r = intersection(p[i], q[i], p[j], q[j]);   //求出交点
                g[i][j] = g[j][i] = on_seg(p[i], q[i], r) && on_seg(p[j], q[j], r);  //交点在两条线段上
            }
        }
    }
    for(int k = 0; k < n; k++){
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n; j++)
                g[i][j] |= g[i][k] && g[k][j];
        }
    }
    for(int i = 0; i < m; i++){
        if(g[a[i]-1][b[i]-1]) cout << "CONNECTED" << endl;
        else                  cout << "NOT CONNECTED" << endl;
    }
}

int main()
{
    while(input()){
        solve();
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/WSS_ang/article/details/80331323