POJ 2653 Pick-up sticks(判断线段相交)

题意 : 有n条线段可能相交,问你最后顶上的线段一共有多少条。

题解 : 关键在于注意到这个题目 top sticks 最多不会超过 1000 这是这个题目的关键,我们可以从前往后依次将可能在顶上的线段放进一个数组里,然后每次对于一条新的线段,枚举判断是否与前面的线段相交相交的话把前面的线段从答案中删除就可以了。

#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 1e6 + 10;
int res[maxn] = {0};
struct seg {
    double x1,y1,x2,y2;
}segment[maxn];
double corss (double x1,double y1,double x2,double y2) {
    return x1 * y2 - x2 * y1;
}
bool judge (seg a,seg b) {
    double ax1 = a.x1,ax2 = a.x2,ay1 = a.y1,ay2 = a.y2;
    double bx1 = b.x1,bx2 = b.x2,by1 = b.y1,by2 = b.y2;
    if (!(max (ax1,ax2) >= min (bx1,bx2) && max (bx1,bx2) >= min (ax1,ax2) && max (ay1,ay2) >= min(by1,by2) && max (by1,by2) >= min(ay1,ay2)) ) return false;
    if (corss(ax2 - ax1, ay2 - ay1, bx1 - ax1, by1 - ay1) * corss(ax2 - ax1, ay2 - ay1, bx2 - ax1, by2 - ay1) < 0) {
        if (corss(bx2 - bx1, by2 - by1, ax1 - bx1, ay1 - by1) * corss(bx2 - bx1, by2 - by1, ax2 - bx1, ay2 - by1) < 0)
            return  true;
    }
    return false;
}
int main () {
    int n;
    while (scanf ("%d",&n) && n) {
        for (int i = 1;i <= n; ++ i) {
            scanf ("%lf%lf%lf%lf",&segment[i].x1,&segment[i].y1,&segment[i].x2,&segment[i].y2);
        }
        int temp = 0;
        for (int i = 1;i <= n; ++ i) {
            int cnt = temp;
            temp = 0;
            for (int j = 0;j < cnt; ++ j) {
                if (!judge(segment[i], segment[res[j]])) {
                    res[temp ++] = res[j];
                }
            }
            res[temp ++] = i;
        }
        int cnt = temp;
        printf ("Top sticks: ");
        for (int i = 0;i < cnt - 1; ++ i) {
            printf ("%d, ",res[i]);
        }
        printf("%d.\n",res[cnt - 1]);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值